python - 如何制作一个新的数据框来存储原始数据框的列箱的平均值?

标签 python pandas dataframe grouping binning

假设我有一个数据框,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 编写每个条目)。

是否有更高效、更简洁的方法来执行此操作?

最佳答案

使用cut对于分立区间的 bin 值,最后聚合 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

关于python - 如何制作一个新的数据框来存储原始数据框的列箱的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51739271/

相关文章:

python - 无法使用 Python 类函数作为按钮命令

python - 尽管已安装,但不会导入 Opus

python - 解析 CSV header

python - 通过多个条件选择行的懒惰方式

python - Pandas 数据透视表 - 新结果表中不同值的不同前缀?

python - pyspark 'DataFrame' 对象没有属性 '_get_object_id'

python - 通过多个内核在 Jupyter Notebook 上运行多个 Python 版本(2.x、3.y、3.z)

python - 错误名称 'dtype' 未定义

python - Pandas:更改数据帧日期索引格式

将第 n 列的列值替换为值与条件匹配的数据帧列表