我正在尝试 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
您能解释一下这种行为吗?我们将不胜感激您的建议。
最佳答案
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
转置()
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_)
或就地
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
关于python - Pandas 上的 fiilna() 方法在 axis=1 上调用时忽略就地参数返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513368/