如何在Pandas中按组计算量子数

141 阅读1分钟

你可以使用下面的基本语法,在Pandas中按组计算量值。

df.groupby('grouping_variable').quantile(.5)

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

例1:按组计算量化指标

假设我们有如下的pandas数据框架:

import pandas as pd

#create DataFrame 
df = pd.DataFrame({'team': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
                   'score': [3, 4, 4, 5, 5, 8, 1, 2, 2, 3, 3, 5]})

#view first five rows
df.head()

team	score
0	1	3
1	1	4
2	1	4
3	1	5
4	1	5 

下面的代码显示了如何计算 "积分 "列中数值的第90个百分位数,并按 "团队 "列进行分组:

df.groupby('team').quantile(.90)

	score
team	
1	6.5
2	4.0

下面是如何解释输出结果的:

  • 第1队的 "积分 "的第90百分位数是6.5
  • 第2队的 "分数 "的第90百分位数是4.0

例2:按组计算几个百分位数

下面的代码显示了如何按组一次计算几个量化指标:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
                   'score': [3, 4, 4, 5, 5, 8, 1, 2, 2, 3, 3, 5]})

#create functions to calculate 1st and 3rd quartiles
def q1(x):
    return x.quantile(0.25)

def q3(x):
    return x.quantile(0.75)

#calculate 1st and 3rd quartiles by group
vals = {'score': [q1, q3]}

df.groupby('team').agg(vals)

	score
        q1	q3
team		
1	4.0	5.0
2	2.0	3.0

下面是如何解释输出结果的:

  • 第1组分数的第一和第三四分位数分别是4.05.0
  • 第2组得分的第一和第三四分位数分别是2.03.0

其他资源

下面的教程介绍了如何在pandas中执行其他常见函数:

如何在Pandas中按组查找最大值
如何在Pandas中按组计算观察值
如何在Pandas中计算列的平均值