Pandas在groupby上组合列

2024-09-24 02:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算在groupby之后合并Pandas数据帧的列。我寻找我可以使用的选项,但没有一个能满足我的要求。最接近的选项是.agg(),它对列的值执行操作,但是,我想为每个给定的groupbyed行计算所有features的统计信息。你知道吗

我在找这样的东西:

dataset.groupby(['company', 'team']).combine(new_cols=['features_mean'], to_combine=['feature 1':'feature 2'], funcs=[np.mean], axis=1)

enter image description here


Tags: 数据信息pandasnew选项meandatasetcompany
2条回答

^{}mean一起使用:

dataset['new measure'] = dataset.loc[:, 'Feature 1':'Feature 12'].mean(axis=1)

样本

dataset = pd.DataFrame({'A':list('abcdef'),
                   'Feature 1':[4,5,4,5,5,4],
                   'Feature 2':[7,8,9,4,2,3],
                   'Feature 3':[1,3,5,7,1,0],
                   'Feature 4':[5,3,6,9,2,4],
                   'F':list('aaabbb')})

#print (dataset)

dataset['new measure'] = dataset.loc[:, 'Feature 1':'Feature 4'].mean(axis=1)
print (dataset)
   A  F  Feature 1  Feature 2  Feature 3  Feature 4  new measure
0  a  a          4          7          1          5         4.25
1  b  a          5          8          3          3         4.75
2  c  a          4          9          5          6         6.00
3  d  b          5          4          7          9         6.25
4  e  b          5          2          1          2         2.50
5  f  b          4          3          0          4         2.75

我意识到我甚至不需要使用groupby。我可以简单地使用apply

dataset['new measure'] = dataset.apply(lambda r: r['Feature 1':'Feature 12'].mean(), axis=1)

This post helped!

但是,由于在implementation中使用了for循环,它运行缓慢。你知道吗

相关问题 更多 >