【发布时间】:2019-01-15 06:44:50
【问题描述】:
假设我有一个数据框,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)]
除了冗长之外,这种方式不适用于更多的 bin(因为我们需要在 new_df 中为每个 bin 编写每个条目)。
有没有更有效、更干净的方法?
【问题讨论】:
标签: python pandas dataframe grouping binning