2015-04-06 67 views
3

与该行的总和替换为NaN我试图与该行的一个数据帧大熊猫的总和来代替楠某些列。请参见下面的示例性数据:如何大熊猫DatatFrame

Items| Estimate1| Estimate2| Estimate3|  
Item1| NaN  |  NaN |   8  
Item2| NaN  | NaN   | 5.5| 

我希望能有估计1 & 2为8和5.5项目1和2分别。

到目前为止,我已经使用df.fillna(df.sum(), inplace=True)尝试,但存在数据帧没有变化。任何人都可以帮助我纠正我的代码或推荐正确的方式来做到这一点吗?

+0

你可以尝试提供'轴= 1'到两个'fillna'和'sum'打电话? – joris

+0

@Joris我试图df.fillna(df.sum(),就地=真,轴= 1),我已经得到了一个错误:“NotImplementedError:目前只能通过柱字典/系列栏中填入” – Avagut

+0

事实上,您对了。请参阅我的回答以获得解决方法 – joris

回答

3

提供axis=1似乎不工作(如用系列填充仅适用于列逐列的情况下,不为行通过行)。
解决方法是将每行的总和“广播”到与原始索引/列具有相同索引/列的数据帧。有了一个稍微修改示例数据框:

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

+0

谢谢!这正是我需要的! – Avagut

0

作为替代方案,你也可以使用一个applylambda表达这样的:

df.apply(lambda row: row.fillna(row.sum()), axis=1) 

产生期望的结果

 Estimate1 Estimate2 Estimate3 
Item1  11.3  3.3  8.0 
Item2  5.5  5.5  5.5 

虽然不确定效率。