【问题标题】:How to replace NaN with sum of the row in Pandas DatatFrame如何用 Pandas DataFrame 中的行总和替换 NaN
【发布时间】:2015-04-06 19:57:31
【问题描述】:

我正在尝试用 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 没有任何变化。任何人都可以帮助我更正我的代码或推荐正确的方法吗?

【问题讨论】:

  • 您能否尝试为fillnasum 通话提供axis=1
  • @Joris 我已经尝试过 df.fillna(df.sum(), inplace=True,axis = 1) 并且我得到一个错误:'NotImplementedError: 目前只能填充 dict/Series 列按列'
  • 确实,你是对的。请参阅我的答案以了解解决方法

标签: python python-3.x pandas dataframe


【解决方案1】:

提供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

【讨论】:

    【解决方案2】:

    您也可以将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
    

    但不确定效率。

    【讨论】:

      猜你喜欢
      • 2016-01-08
      • 2018-11-14
      • 2023-01-24
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多