python pandas:如何根据列中的每个值进行分组并计数? [英] python pandas: how to group by and count with a condition for every value in a column?

查看:5724
本文介绍了python pandas:如何根据列中的每个值进行分组并计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的表:

I have table like this:

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

我喜欢迭代d的值和具有组= a的行的计数数目。

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?

推荐答案

try:

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.

这篇关于python pandas:如何根据列中的每个值进行分组并计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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