我正在尝试将某些列中的 NaN 替换为 Pandas DataFrame 中行的总和。请参阅下面的示例数据:
Items| Estimate1| Estimate2| Estimate3|
Item1| NaN | NaN | 8
Item2| NaN | NaN | 5.5|
我希望项目 1 和项目 2 的估计值 1 和 2 分别为 8 和 5.5。
到目前为止,我已尝试使用 df.fillna(df.sum(), inplace=True)
但 DataFrame 没有任何变化。任何人都可以帮助我更正我的代码或推荐正确的方法吗?
最佳答案
提供 axis=1
似乎不起作用(因为填充 Series 仅适用于逐列的情况,不适用于逐行的情况)。
一种解决方法是将每一行的总和“广播”到与原始数据帧具有相同索引/列的数据帧。使用稍微修改过的示例数据框:
In [57]: df = pd.DataFrame([[np.nan, 3.3, 8], [np.nan, np.nan, 5.5]], index=['Item1', 'Item2'], columns=['Estimate1', 'Estimate2', 'Estimate3'])
In [58]: df
Out[58]:
Estimate1 Estimate2 Estimate3
Item1 NaN 3.3 8.0
Item2 NaN NaN 5.5
In [59]: fill_value = pd.DataFrame({col: df.sum(axis=1) for col in df.columns})
In [60]: fill_value
Out[60]:
Estimate1 Estimate2 Estimate3
Item1 11.3 11.3 11.3
Item2 5.5 5.5 5.5
In [61]: df.fillna(fill_value)
Out[61]:
Estimate1 Estimate2 Estimate3
Item1 11.3 3.3 8.0
Item2 5.5 5.5 5.5
有一个开放的增强问题:https://github.com/pydata/pandas/issues/4514
关于python - 如何用 Pandas DataFrame 中行的总和替换 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29478641/