Pandas在groupby上组合了列

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

我打算在groupby之后组合Pandas DataFrame的列。我找了一些我可以使用的选项,但没有一个能做我正在寻找的东西。最接近的选项是.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

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

使用locmean

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

0
投票

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

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

This post helped!

然而,由于在for中使用implementation循环,它运行缓慢。

© www.soinside.com 2019 - 2024. All rights reserved.