>>> 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)]
除了冗长之外,这种方式不能很好地扩展到更多的bin(因为我们需要为new_df中的每个bin写入每个条目).
这样做是否有更高效,更干净的方式?
解决方法:
使用cut
将bin值转换为离散间隔,最后聚合均值:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。