熊猫数据框:用行平均值替换NaN
我正在尝试学习熊猫,但请对以下内容感到困惑.我想用行平均值替换NaNs是一个数据框.因此,像df.fillna(df.mean(axis=1))
这样的东西应该可以工作,但是由于某种原因它对我来说却失败了.我是否想念任何东西,我做错了什么?是因为其未执行;参见链接此处
I am trying to learn pandas but i have been puzzled with the following please. I want to replace NaNs is a dataframe with the row average. Hence something like df.fillna(df.mean(axis=1))
should work but for some reason it fails for me. Am I missing anything please, something I'm doing wrong? Is is because its not implemented; see link here
import pandas as pd
import numpy as np
pd.__version__
Out[44]:
'0.15.2'
In [45]:
df = pd.DataFrame()
df['c1'] = [1, 2, 3]
df['c2'] = [4, 5, 6]
df['c3'] = [7, np.nan, 9]
df
Out[45]:
c1 c2 c3
0 1 4 7
1 2 5 NaN
2 3 6 9
In [46]:
df.fillna(df.mean(axis=1))
Out[46]:
c1 c2 c3
0 1 4 7
1 2 5 NaN
2 3 6 9
但是类似的东西看起来可以正常工作
However something like this looks to work fine
df.fillna(df.mean(axis=0))
Out[47]:
c1 c2 c3
0 1 4 7
1 2 5 8
2 3 6 9
As commented the axis argument to fillna is NotImplemented.
df.fillna(df.mean(axis=1), axis=1)
注意:这在这里非常重要,因为您不想用第n行平均值填写第n列.
现在您需要遍历:
In [11]: m = df.mean(axis=1)
for i, col in enumerate(df):
# using i allows for duplicate columns
# inplace *may* not always work here, so IMO the next line is preferred
# df.iloc[:, i].fillna(m, inplace=True)
df.iloc[:, i] = df.iloc[:, i].fillna(m)
In [12]: df
Out[12]:
c1 c2 c3
0 1 4 7.0
1 2 5 3.5
2 3 6 9.0
另一种方法是先填充转置然后再转置,这样可能会更有效...
An alternative is to fillna the transpose and then transpose, which may be more efficient...
df.T.fillna(df.mean(axis=1)).T