我尝试从数据框中计算特定的分位数值,如下面的代码所示。分行计算没有问题。
尝试运行最后两行时,出现以下错误:
AttributeError: 'SeriesGroupBy' object has no attribute 'quantile(0.25)'
我该如何解决这个问题?
import pandas as pd
df = pd.DataFrame(
{
'x': [0, 1, 0, 1, 0, 1, 0, 1],
'y': [7, 6, 5, 4, 3, 2, 1, 0],
'number': [25000, 35000, 45000, 50000, 60000, 70000, 65000, 36000]
}
)
f = {'number': ['median', 'std', 'quantile']}
df1 = df.groupby('x').agg(f)
df.groupby('x').quantile(0.25)
df.groupby('x').quantile(0.75)
# code below with problem:
f = {'number': ['median', 'std', 'quantile(0.25)', 'quantile(0.75)']}
df1 = df.groupby('x').agg(f)
最佳答案
我更喜欢 def 函数
def q1(x):
return x.quantile(0.25)
def q3(x):
return x.quantile(0.75)
f = {'number': ['median', 'std', q1, q3]}
df1 = df.groupby('x').agg(f)
df1
Out[1643]:
number
median std q1 q3
x
0 52500 17969.882211 40000 61250
1 43000 16337.584481 35750 55000
关于python - Pandas groupby 分位数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637774/