Pandas上的fiilna()方法在轴= 1上调用时忽略inplace参数返回错误

时间:2017-01-06 19:56:51

标签: python pandas nan

我正在尝试使用fillna()方法。我为此创建了一个小型数据框和两个系列:

   col1    col2    col3      col4
0  NaN      NaN    3           4
1  NaN      NaN    7           8
2  9.0     10.0    11         12

n1 = pd.Series([10, 20])
n2 = pd.Series([30, 40, 50, 60])
n2.index = list(df.columns.values)

当我尝试命令时:

df.fillna(n1, axis=0, inplace = True)

没有任何事情发生,NaN仍然完好无损。我希望看到它们被替换为值10(col1)和20(col2)。当我尝试

df.fillna(n2, axis =1)

我收到错误消息:

NotImplementedError: Currently only can fill with dict/Series column by column

你能解释一下这种行为吗?您的建议将不胜感激。

2 个答案:

答案 0 :(得分:2)

fillna的默认轴是0。这转换为将列与要传递的系列的索引进行匹配。这意味着填写n2应该在axis=0

df.fillna(n2)  # axis=0 is default

   col1  col2  col3  col4
0  30.0  40.0     3     4
1  30.0  40.0     7     8
2   9.0  10.0    11    12

这样做inplace=True肯定有效

df.fillna(n2, inplace=True)
print(df)

   col1  col2  col3  col4
0  30.0  40.0     3     4
1  30.0  40.0     7     8
2   9.0  10.0    11    12
df.fillna(n1, axis=1)

NotImplementedError: Currently only can fill with dict/Series column by column

呀!你运气不好......有点

选项1
transpose()

df.T.fillna(n1).T

   col1  col2  col3  col4
0  10.0  10.0   3.0   4.0
1  20.0  20.0   7.0   8.0
2   9.0  10.0  11.0  12.0

选项2
使用尴尬的pandas广播

n1_ = pd.DataFrame([n1], index=df.columns).T
df.fillna(n1_)

inplace

df.fillna(n1_, inplace=True)
df

   col1  col2  col3  col4
0  10.0  10.0     3     4
1  20.0  20.0     7     8
2   9.0  10.0    11    12

答案 1 :(得分:0)

您想要指定要填充值的列。例如,

df['col1'].fillna(n1, inplace=True)

df
Out[17]: 
   col1  col2  col3  col4
0    10   NaN     3     4
1    20   NaN     7     8
2     9    10    11    12

在您填写单个值的实例中,例如0,您可以像上面那样将其应用于DataFrame。从原始DataFrame开始,

df.fillna(0, inplace=True)

df
Out[27]: 
   col1  col2  col3  col4
0     0     0     3     4
1     0     0     7     8
2     9    10    11    12