gpt4 book ai didi

python - 如何在Python中计算pandas数据帧的标准差

转载 作者:行者123 更新时间:2023-12-01 01:20:57 24 4
gpt4 key购买 nike

我想计算数据帧的标准偏差,然后合并它,像这样

std = all_data.groupby(['Id'])[features].agg('std')
all_data = pd.merge(all_data, std.reset_index(), suffixes=["", "_std"], how='left', on=['Id'])

但是没有任何东西像.agg('std')

最佳答案

您的解决方案对我来说效果很好。

我认为你需要transform为了避免对与原始 DataFrame 大小相同的新 Series 使用 merge:

all_data = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'Id':list('aaabbb')
})

#print (all_data)

features = ['B','C','D']
#new columns names
cols = ['{}_std'.format(x) for x in features]
#python 3.6+ solution with f-strings
#cols = [f'{x}_std' for x in features]

all_data[cols] = all_data.groupby(['Id'])[features].transform('std')
print (all_data)
A B C D E Id B_std C_std D_std
0 a 4 7 1 5 a 0.57735 1 2.000000
1 b 5 8 3 3 a 0.57735 1 2.000000
2 c 4 9 5 6 a 0.57735 1 2.000000
3 d 5 4 7 9 b 0.57735 1 3.785939
4 e 5 2 1 2 b 0.57735 1 3.785939
5 f 4 3 0 4 b 0.57735 1 3.785939

关于python - 如何在Python中计算pandas数据帧的标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53851015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com