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 1   Score 2     Score 3
19-21     2         4           3
22-24     2         2           9

这是我的做法,我觉得非常复杂(意思是,它不应该这么困难):

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)

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

df = pd.DataFrame(columns=['Score', labels[0], labels[1]])
df['Score'] = data.Score.unique()
for i in labels:
    df[i] = np.zeros(3)


for i in range(len(data)):
    for j in range(len(labels)):
        m1, m2 = labels[j].split('-') # lower & upper bounds of the age interval
        if ((float(data['Age'][i])>float(m1)) & (float(data['Age'][i])<float(m2))): # find the age group in which each age lies
            if data['Score'][i]==1:
                index = 0
            elif data['Score'][i]==2:
                index = 1
            elif data['Score'][i]==3:
                index = 2

            df[labels[j]][index] += 1

df.sort_values('Score', inplace=True)
df.set_index('Score', inplace=True)
print(df)

这会产生

             19.0-21.5      22.5-24.0
Score                      
1            2.0            2.0
2            4.0            2.0
3            3.0            9.0

是否有更好、更干净、更高效的方法来实现这一目标?

最佳答案

IIUC,我想你可以尝试以下之一:

1.如果您已经知道垃圾箱:

df['Age'] = np.where(df['Age']<=21,'19-21','22-24')
df.groupby(['Age'])['Score'].value_counts().unstack()

2.如果您知道所需的垃圾箱数量:

df.Age = pd.cut(df.Age, bins=2,include_lowest=True)
df.groupby(['Age'])['Score'].value_counts().unstack()

3. Jon Clements来自评论的想法:

pd.crosstab(pd.cut(df.Age, [19, 21, 24],include_lowest=True), df.Score)

这三个都会产生以下输出:

Score           1   2   3
Age         
(18.999, 21.0]  3   2   1
(21.0, 24.0]    2   1   3

关于python - 对数据框的一列进行分箱后,如何创建一个新的数据框来计算每个箱中的元素数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51745831/

相关文章:

pandas - 使用 multiindex 更改 pandas DataFrame 中的索引顺序

python - Pandas:显示列表的总和

python - 无法在ubuntu中通过python设置环境变量

python - AWS Lambda 函数触发两次

python - Pandas 打印选项

python - 在计数图上绘制折线图,​​右侧有单独的 y 轴

python - 如何使用 Python 下载股票价格数据?

python - 来自列表中字典的字典的数据框

python - 如何计算任何 datetime64 列的第二天分钟差?

python - 如何从两列中提取数字范围并将两列中的范围打印为元组?