pandas DataFrame: reemplazar los valores nan con el promedio de columnas
Tengo un DataFrame de pandas lleno principalmente de números reales, pero también hay algunos valores nan
.
¿Cómo puedo reemplazar los nan
s con promedios de las columnas donde están?
Esta pregunta es muy similar a esta: matriz numpy: reemplace los valores nan con el promedio de columnas pero, desafortunadamente, la solución dada allí no funciona para un DataFrame de pandas.
7 answers
Simplemente puede usar DataFrame.fillna
para rellenar los nan
's directamente:
In [27]: df
Out[27]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 NaN -2.027325 1.533582
4 NaN NaN 0.461821
5 -0.788073 NaN NaN
6 -0.916080 -0.612343 NaN
7 -0.887858 1.033826 NaN
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
In [28]: df.mean()
Out[28]:
A -0.151121
B -0.231291
C -0.530307
dtype: float64
In [29]: df.fillna(df.mean())
Out[29]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 -0.151121 -2.027325 1.533582
4 -0.151121 -0.231291 0.461821
5 -0.788073 -0.231291 -0.530307
6 -0.916080 -0.612343 -0.530307
7 -0.887858 1.033826 -0.530307
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
El docstring de fillna
dice que value
debe ser un escalar o un dict, sin embargo, parece funcionar con un Series
también. Si quieres pasar un dict, puedes usar df.mean().to_dict()
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-19 17:49:12
Intenta:
sub2['income'].fillna((sub2['income'].mean()), inplace=True)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-16 20:30:12
In [16]: df = DataFrame(np.random.randn(10,3))
In [17]: df.iloc[3:5,0] = np.nan
In [18]: df.iloc[4:6,1] = np.nan
In [19]: df.iloc[5:8,2] = np.nan
In [20]: df
Out[20]:
0 1 2
0 1.148272 0.227366 -2.368136
1 -0.820823 1.071471 -0.784713
2 0.157913 0.602857 0.665034
3 NaN -0.985188 -0.324136
4 NaN NaN 0.238512
5 0.769657 NaN NaN
6 0.141951 0.326064 NaN
7 -1.694475 -0.523440 NaN
8 0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794
In [22]: df.mean()
Out[22]:
0 -0.251534
1 -0.040622
2 -0.841219
dtype: float64
Aplique por columna la media de esas columnas y rellene
In [23]: df.apply(lambda x: x.fillna(x.mean()),axis=0)
Out[23]:
0 1 2
0 1.148272 0.227366 -2.368136
1 -0.820823 1.071471 -0.784713
2 0.157913 0.602857 0.665034
3 -0.251534 -0.985188 -0.324136
4 -0.251534 -0.040622 0.238512
5 0.769657 -0.040622 -0.841219
6 0.141951 0.326064 -0.841219
7 -1.694475 -0.523440 -0.841219
8 0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-09 00:15:05
# To read data from csv file
Dataset = pd.read_csv('Data.csv')
# To divide input in X and y axis
X = Dataset.iloc[:, :-1].values
Y = Dataset.iloc[:, 3].values
# To calculate mean use imputer class
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN', strategy='mean', axis=0)
imputer = imputer.fit(X[:, 1:3])
X[:, 1:3] = imputer.transform(X[:, 1:3])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 22:27:24
Otra opción además de las anteriores es:
df = df.groupby(df.columns, axis = 1).transform(lambda x: x.fillna(x.mean()))
Es menos elegante que las respuestas anteriores para mean, pero podría ser más corto si desea reemplazar los nulos por alguna otra función de columna.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-15 19:40:34
Si desea imputar los valores faltantes con la media y desea ir columna por columna, entonces esto solo imputará con la media de esa columna. Esto podría ser un poco más legible.
sub2['income'] = sub2['income'].fillna((sub2['income'].mean()))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 22:27:54
Utilice directamente df.fillna(df.mean())
para rellenar todo el valor nulo con mean
Si desea llenar el valor nulo con la media de esa columna, puede usar esto
Supongamos que x=df['Item_Weight']
aquí Item_Weight
es el nombre de la columna
Aquí estamos asignando (rellene los valores nulos de x con la media de x en x)
df['Item_Weight'] = df['Item_Weight'].fillna((df['Item_Weight'].mean()))
Si desea rellenar el valor null con alguna cadena, utilice
Aquí Outlet_size
está el nombre de la columna
df.Outlet_Size = df.Outlet_Size.fillna('Missing')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-27 22:28:39