如何创建一个新的数据框来存储原始数据框列分组后的平均值?

3

假设我有一个数据框,df:

>>> df

Age    Score
19     1
20     2
24     3
19     2
24     3
24     1
24     3
20     1
19     1
20     3
22     2
22     1

我想构建一个新的数据框,对 Age 进行分组,并将它们在这些区间的平均分数存储在 Score 中:

Age       Score
19-21     1.6667
22-24     2.1667

这是我认为有点复杂的做法:

import numpy as np
import pandas as pd

data = pd.DataFrame(columns=['Age', 'Score'])
data['Age'] = [19,20,24,19,24,24,24,20,19,20,22,22]
data['Score'] = [1,2,3,2,3,1,3,1,1,3,2,1]

_, bins = np.histogram(data['Age'], 2)

df1 = data[data['Age']<int(bins[1])]
df2 = data[data['Age']>int(bins[1])]

new_df = pd.DataFrame(columns=['Age', 'Score'])
new_df['Age'] = [str(int(bins[0]))+'-'+str(int(bins[1])), str(int(bins[1]))+'-'+str(int(bins[2]))]
new_df['Score'] = [np.mean(df1.Score), np.mean(df2.Score)]

除了冗长外,这种方法在需要更多垃圾箱时不会很好地扩展(因为我们需要为new_df中的每个垃圾箱编写每个条目)。
有没有更有效、更清晰的方法来做这件事?
1个回答

5

使用cut函数将数值分段,然后用mean函数求每个区间的平均数:

bins = [19, 21, 24]
#dynamically create labels
labels = ['{}-{}'.format(i + 1, j) for i, j in zip(bins[:-1], bins[1:])] 
labels[0] = '{}-{}'.format(bins[0], bins[1])
print (labels)
['19-21', '22-24']

binned = pd.cut(data['Age'], bins=bins, labels=labels, include_lowest=True)
df = data.groupby(binned)['Score'].mean().reset_index()
print (df)
     Age     Score
0  19-21  1.666667
1  22-24  2.166667

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接