Pandas 上的 fiilna() 方法在 axis=1 上调用时忽略就地参数 returns 错误

fiilna() method on Pandas ignores inplace argument returns error when called on axis=1

我正在试验 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

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

您要指定要为其填写值的列。例如,

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

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