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

标签 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

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

最佳答案

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/

相关文章:

python - 如何有效地将 NaN 放入 Pandas Dataframe 中?

python - 在 DARKNET 训练期间得到 -NaN,我做错了什么?

python - 在 Django 1.3 media_url 与 static_url 中显示样式

python - 执行外部应用程序并向其发送一些关键事件

python - 带有 Python 的 jupyter 实验室中函数的参数

python - 返回与列中另一个数据帧具有不同值的行

javascript - NaN 出矩阵乘法?

python - 在 Django 中,保存到数据库时如何返回现有模型实例

python - 使用 python 将多个工作表中的数据添加到 Excel 图表中

python - Pandas 在不应该返回 NaT 的情况下返回 NaT