如何将用户自定义函数按列应用于大熊猫中的分组数据

问题描述 投票:0回答:2

如何将用户定义的函数列明智地应用于熊猫中的分组数据。用户定义的函数返回一系列固定形状。

def getStats(col):
names = ['mean', 'std']
return pd.Series([np.mean(col), np.std(col)], index = names, name = col.name)

df = pd.DataFrame({'city':['c1','c2','c1','c2'],
               'age':[10,20,30,40],
               'sal':[1000,2000,3000,4000]})

grp_data = df.groupby('city')
grp_data.apply(getStats)

我已经尝试过上述片段。但是我没有得到预期格式的结果。

城市|级别|年龄|萨尔

c1 |意思x | y

c2 |标准| x1 | y1

请您帮忙。

python pandas pandas-groupby
2个回答
0
投票

我认为自定义功能不是必需的,而是由GroupBy.agg进行聚合,并带有聚合函数列表,并由GroupBy.agg进行整形,最后DataFrame.stack用于DataFrame.stackDataFrame.rename_axis标签:

DataFrame.rename_axis

0
投票

您可以从Series中稍微更改功能以返回数据帧,并将city列表更改为已命名的Series。

level

df = df.groupby('city').agg([np.mean,np.std]).stack().rename_axis(['city','level'])
print (df)
                  age          sal
city level                        
c1   mean   20.000000  2000.000000
     std    14.142136  1414.213562
c2   mean   30.000000  3000.000000
     std    14.142136  1414.213562
© www.soinside.com 2019 - 2024. All rights reserved.