微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 分组并查找组的总和,但返回NaN为NaN,而不是0

我有一个数据框,每个唯一的组有4行.
所以我需要按列进行分组,使它们成为唯一的,并进行一些聚合,例如max,min,sum和average.
但问题是我为某些组提供了所有NaN值(在某些列中)并返回0.是否有可能返回NaN?
例如:
DF

       time            id     el    conn   column1  column2  column3
2018-02-11 14:00:00     1     a      12      8        5         NaN
2018-02-11 14:00:00     1     a      12      1        NaN       NaN
2018-02-11 14:00:00     1     a      12      3        7         NaN
2018-02-11 14:00:00     1     a      12      4        12        NaN
2018-02-11 14:00:00     2     a      5       NaN      5         5
2018-02-11 14:00:00     2     a      5       NaN      3         2
2018-02-11 14:00:00     2     a      5       NaN      NaN       6
2018-02-11 14:00:00     2     a      5       NaN      7         NaN

因此,例如,我需要groupby(‘id’,’el’,’conn’)并找到column1,column3和column2的和. (在实际情况下,我需要执行更多的列聚合).
我尝试了几种方法:.sum(),. transnsform(‘sum’),但是对于具有所有NaN值的组,我返回零.

期望的输出

    time               id    el     conn   column1  column2  column3
2018-02-11 14:00:00     1     a      12      16       24       NaN
2018-02-11 14:00:00     2     a      5       NaN      15        13

欢迎任何帮助.

解决方法:

将参数min_count更改为1 – 这在last pandas version 0.22.0中有效:

min_count : int, default 0

The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

New in version 0.22.0: Added with the default being 1. This means the sum or product of an all-NA or empty series is NaN.

df = df.groupby(['time','id', 'el', 'conn'], as_index=False).sum(min_count=1)
print (df)
                  time  id el  conn  column1  column2  column3
0  2018-02-11 14:00:00   1  a    12     16.0     24.0      NaN
1  2018-02-11 14:00:00   2  a     5      NaN     15.0     13.0

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐