pandas 分组计数,然后条件平均 [英] pandas groupby count and then conditional mean

查看:59
本文介绍了 pandas 分组计数,然后条件平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a dataframe like this:

    col1 col2
0    a   100
1    a   200
2    a   150
3    b   1000
4    c   400
5    c   200

我想要做的是按 col1 分组并计算出现次数,如果计数等于或大于 2,则计算这些行的 col2 的平均值,如果不是则返回 null.输出应该是:

what I want to do is group by col1 and count the number of occurrences and if count is equal or greater than 2, then calculate mean of col2 for those rows and if not returns null. The output should be:

    col1 mean
0    a   150
1    b   
2    c   300

推荐答案

使用 groupby.mean + DataFrame.whereSeries.value_counts:

df.groupby('col1').mean().where(df['col1'].value_counts().ge(2)).reset_index()

#you can select columns you want
#(df.groupby('col1')[['col2']]
#   .mean()
#   .where(df['col1'].value_counts().ge(2)).reset_index())

输出

  col1   col2
0    a  150.0
1    b    NaN
2    c  300.0

<小时>

如果你真的想要空格:


if you really want blanks:

df.groupby('col1').mean().where(df['col1'].value_counts().ge(2), '').reset_index()

  col1 col2
0    a  150
1    b     
2    c  300

这篇关于 pandas 分组计数,然后条件平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆