如何在Pandas数据框架中添加计数列

510 阅读2分钟

你可以使用下面的基本语法在pandas DataFrame中添加一个 "计数 "列:

df['var1_count'] = df.groupby('var1')['var1'].transform('count')

这种特殊的语法在DataFrame中添加了一个名为var1_count的列,其中包含了名为var1的列中数值的计数。

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

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

假设我们有如下的pandas DataFrame,其中包含各种篮球运动员的信息:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', '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    B  Fo      14
4    B  Gu      14
5    B  Gu      11
6    B  Fo      20
7    B  Fo      28

我们可以使用下面的代码来添加一个名为team_count的列,其中包含每个球队的计数:

#add column that shows total count of each team
df['team_count'] = df.groupby('team')['team'].transform('count')

#view updated DataFrame
print(df)

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

3行的球队值为A,有5行的球队值为B。

因此:

  • 对于团队等于A的每一行,team_count列的值是3
  • 对于每一行的球队等于B,team_count列中的值是5

你也可以添加一个 "计数 "列,按多个变量分组。

例如,下面的代码显示了如何添加一个按团队位置变量分组的'计数'列。

#add column that shows total count of each team and position
df['team_pos_count'] = df.groupby(['team', 'pos')['team'].transform('count')

#view updated DataFrame
print(df)

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

从输出中我们可以看到:

  • 1行在团队列中包含A,在位置列中包含Gu
  • 2行在团队列中包含A,在位置列中包含F
  • 3行在团队列中包含B,在位置列中包含F
  • 2行在团队列中包含B,在位置列中包含Gu

其他资源

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

Pandas:如何使用GroupBy和值计数
Pandas:如何使用GroupBy与Bin计数
Pandas:如何用条件计数列中的值