Pandas:Replacing 有效地对具有代表性值的列进行分箱

Pandas:Replacing binned columns with representative value efficiently

我想对数据进行分箱,select每个分箱的特定聚合。

import pandas as pd
df = pd.DataFrame({ 
  'A': [1, 2, 3, 4],
  'B': [1, 2, 3, 4],
})
groups = pd.cut(df['A'], bins=2, labels=False)
group_reps = df.groupby([groups]).agg(A=('A', 'mean'))
# ... some magic happens here to replace values in A by group_reps ...
# 
# expected result
# A, B
# 1.5, 1
# 1.5, 2
# 3.5, 3
# 3.5, 4

对于大小接近机器内存的数据,如何有效地实现?

如果你想改变一列,你可以单独处理。此外,transform 可帮助您将聚合与原始索引对齐:

df['A'] = df['A'].groupby(groups).transform('mean')