[英]How to replace NaN with sum of the row in Pandas DatatFrame
我試圖用Pandas DataFrame中的行的總和替換某些列中的NaN。 請參見下面的示例數據:
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
似乎不起作用(因為填充系列僅適用於逐列的情況,而不適用於逐行)。
解決方法是將每行的總和“廣播”到與原始索引/列具有相同索引/列的數據幀。 使用稍微修改的示例數據幀:
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
作為替代方案,您還可以使用帶有lambda
表達式的apply
,如下所示:
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
雖然不確定效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.