python pandas: how to group by and count with a condition for every value in a column?

狂风中的少年 提交于 2019-12-13 21:26:51

问题


I have table like this:

d  group
1   a
2   b
3   a
4   c
5   f

and I like to iterate over values of d and count number of rows that have group=a .

Here is what I am doing now, but It does not work:

for index,row in df.iterrows():
    for x in (1,5):
        if row['d'] > x:
            row['tp'] = df.groupby('group').agg(lambda x:x.manual_type=='a')

Can anybody help?


回答1:


try:

df['group'].value_counts()['a']

in general, you should NEVER use for loops in pandas. it's inefficient and usually recreating some existing functionality in the package.



来源:https://stackoverflow.com/questions/31458703/python-pandas-how-to-group-by-and-count-with-a-condition-for-every-value-in-a-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!