【问题标题】:Pandas: Sum multiple columns, but write NaN if any column in that row is NaN or 0Pandas:对多列求和,但如果该行中的任何列是 NaN 或 0,则写 NaN
【发布时间】:2018-12-02 05:05:33
【问题描述】:

我正在尝试在 Pandas 数据框中创建一个新列,用于汇总其他列的总数。但是,如果任何源列为空白(NaN 或 0),我需要将新列也写为空白(NaN)

a    b    c    d    sum

3    5    7    4    19
2    6    0    2    NaN    (note the 0 in column c)
4    NaN  3    7    NaN

我目前正在使用 pd.sum 函数,格式如下

 df['sum'] = df[['a','b','c','d']].sum(axis=1, numeric_only=True)

忽略 NaN,但不将 NaN 写入 sum 列。

提前感谢您的任何建议

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    replace 你的 0 到 np.nan 然后通过 skipna = False

    df.replace(0,np.nan).sum(1,skipna=False)
    0    19.0
    1     NaN
    2     NaN
    dtype: float64
    df['sum'] = df.replace(0,np.nan).sum(1,skipna=False)
    

    【讨论】:

    • 成功了,非常感谢!我显然有很多关于 pandas 的知识要学习,所以非常感谢您的帮助!
    猜你喜欢
    • 2022-01-26
    • 2021-12-18
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2020-11-04
    • 2016-12-31
    • 2021-02-20
    相关资源
    最近更新 更多