熊猫:如何使用Groupby和带条件计数

325 阅读2分钟

你可以使用下面的基本语法在pandas DataFrame中执行groupby和带条件计数。

df.groupby('var1')['var2'].apply(lambda x: (x=='val').sum()).reset_index(name='count')

这个特殊的语法是根据var1对DataFrame的行进行分组,然后计算var2等于'val'的行的数量。

下面的例子展示了如何在实践中使用这种语法。

例子。Pandas中的Groupby和带条件计数

假设我们有如下的pandas数据框架,其中包含各种篮球运动员的信息。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
                   'pos': ['Gu', 'Fo', 'Fo', 'Fo', 'Gu', 'Gu', 'Fo', 'Fo'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28]})

#view DataFrame
print(df)

  team pos  points
0    A  Gu      18
1    A  Fo      22
2    A  Fo      19
3    A  Fo      14
4    B  Gu      14
5    B  Gu      11
6    B  Fo      20
7    B  Fo      28

下面的代码显示了如何通过团队变量对DataFrame进行分组,并计算pos变量等于 "Gu "的行数。

#groupby team and count number of 'pos' equal to 'Gu'
df_count = df.groupby('team')['pos'].apply(lambda x: (x=='Gu').sum()).reset_index(name='count')

#view results
print(df_count)

  team  count
0    A      1
1    B      2

从输出中我们可以看到。

  • 球队A有1行,其中pos列等于'Gu'。
  • 团队B有2行,其中pos列等于'Gu'。

我们可以使用类似的语法来执行groupby和带有一些数字条件的计数。

例如,下面的代码显示了如何通过团队变量进行分组,并计算积分 变量大于15的行的数量。

#groupby team and count number of 'points' greater than 15
df_count = df.groupby('team')['points'].apply(lambda x: (x>15).sum()).reset_index(name='count')

#view results
print(df_count)

  team  count
0    A      3
1    B      2

从输出中我们可以看到。

  • 团队A有3行积分列大于15的记录
  • 球队B有2行积分列大于15的记录。

你可以使用类似的语法来执行groupby和计数,并使用任何你想要的特定条件。

其他资源

下面的教程解释了如何在pandas中执行其他常见任务。

如何使用Pandas GroupBy计算唯一值
如何将函数应用于Pandas Groupby
如何通过Pandas GroupBy创建条形图

The postPandas: How to Use Groupby and Count with Conditionappeared first onStatology.