在Pandas Dataframe上进行groupby之后如何进行条件计数? [英] How to do a conditional count after groupby on a Pandas Dataframe?
本文介绍了在Pandas Dataframe上进行groupby之后如何进行条件计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据框:
key1 key2
0 a one
1 a two
2 b one
3 b two
4 a one
5 c two
现在,我想按key1
对数据帧进行分组,并用值"one"
对列key2
进行计数,以获得以下结果:
Now, I want to group the dataframe by the key1
and count the column key2
with the value "one"
to get this result:
key1
0 a 2
1 b 1
2 c 0
我只是得到通常的计数:
I just get the usual count with:
df.groupby(['key1']).size()
但是我不知道如何插入条件.
But I don't know how to insert the condition.
我尝试过这样的事情:
df.groupby(['key1']).apply(df[df['key2'] == 'one'])
但是我不能再进一步了.我该怎么办?
But I can't get any further. How can I do this?
推荐答案
我认为您需要先添加条件:
I think you need add condition first:
#if need also category c with no values of 'one'
df11=df.groupby('key1')['key2'].apply(lambda x: (x=='one').sum()).reset_index(name='count')
print (df11)
key1 count
0 a 2
1 b 1
2 c 0
或将 categorical
与key1
一起使用,然后丢失值由size
添加:
Or use categorical
with key1
, then missing value is added by size
:
df['key1'] = df['key1'].astype('category')
df1 = df[df['key2'] == 'one'].groupby(['key1']).size().reset_index(name='count')
print (df1)
key1 count
0 a 2
1 b 1
2 c 0
如果需要所有组合:
If need all combinations:
df2 = df.groupby(['key1', 'key2']).size().reset_index(name='count')
print (df2)
key1 key2 count
0 a one 2
1 a two 1
2 b one 1
3 b two 1
4 c two 1
df3 = df.groupby(['key1', 'key2']).size().unstack(fill_value=0)
print (df3)
key2 one two
key1
a 2 1
b 1 1
c 0 1
这篇关于在Pandas Dataframe上进行groupby之后如何进行条件计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文