我有一个这样的数据框:
col1 col2
0 a 100
1 a 200
2 a 150
3 b 1000
4 c 400
5 c 200
我想要做的是按col1分组并计算出现的次数,如果count等于或大于2,则计算这些行的col2平均值,如果不返回null。输出应为:
col1 mean
0 a 150
1 b
2 c 300
使用groupby.mean
+DataFrame.where
有Series.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
如果您真的想要空白:
df.groupby('col1').mean().where(df['col1'].value_counts().ge(2), '').reset_index()
col1 col2
0 a 150
1 b
2 c 300
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句