由于您没有指定垃圾箱的数量及其属性,让我来说明您可以使用 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