【问题标题】:python : aggregate dataframe values by binpython:按 bin 聚合数据帧值
【发布时间】:2022-11-18 03:03:51
【问题描述】:

我有一个看起来像这样的数据集:

|col A|col B|
   1     20
   3    123
   7     2
     ...

我想计算 col A 的每个 bin 上的 col B 的平均值。

这将产生一个新的数据框,每个 bin 只包含一行:

 | mid value of the col A bin | avg value of col B over that bin |

【问题讨论】:

  • 你能制作至少 5 行示例和所需的输出吗?
  • 您的装箱规则是什么? pandas.cut 可能是个不错的选择。

标签: python pandas dataframe binning


【解决方案1】:

由于您没有指定垃圾箱的数量及其属性,让我来说明您可以使用 pandas.cut 对您提供的示例数据执行的操作:

import pandas as pd

# reproduce your example data
df = pd.DataFrame({'col A': [1, 3, 7],
                   'col B': [20, 123, 2]})

# suggest only 2 bins would be proper for 3 rows of data
df['col A bins'] = pd.cut(df['col A'], 
                          bins=2)

输出:

# bins may be labeled as you like, not as automatic interval
    col A   col B   col A bins
0   1       20      (0.994, 4.0]
1   3       123     (0.994, 4.0]
2   7       2       (4.0, 7.0]

然后我们可以按新的 bins 对初始列进行分组,col A 聚合到中位数(从您的新列名开始)和 col B 表示,通过重命名和删除列使其看起来像您的预期结果:

df.groupby('col A bins').agg({'col A': 'median',
                              'col B': 'mean'}
                       ).rename(columns={'col A':'mid value of the col A bin',
                                         'col B':'avg value of col B over that bin'}
                       ).reset_index(drop=True)

输出:

    mid value of the col A bin  avg value of col B over that bin
0   2.0                         71.5
1   7.0                         2.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多