python - 在所有数据帧列上应用不同 bin 大小的 binning

标签 python pandas dataframe binning

我有一个小问题。我有一个非常大的 df,有很多列。我正在尝试找到最有效的方法来对具有不同 bin 大小的所有列进行 bin 并创建一个新的 df.以下是仅对单个列进行分箱的示例:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,20,size=(5, 4)), columns=list('ABCD'))
newDF = pd.cut(df.A, 2, precision=0)
newDF 
0    (9.0, 18.0]
1    (-0.0, 9.0]
2    (-0.0, 9.0]
3    (-0.0, 9.0]
4    (9.0, 18.0]
Name: A, dtype: category
Categories (2, interval[float64]): [(-0.0, 9.0] < (9.0, 18.0]]

最佳答案

如果想单独处理每一列,请使用 DataFrame.apply :

df = pd.DataFrame(np.random.randint(0,20,size=(5, 4)), columns=list('ABCD'))
newDF = df.apply(lambda x: pd.cut(x, 2, precision=0))
print (newDF)
            A            B             C             D
0  (2.0, 4.0]  (8.0, 15.0]   (7.0, 13.0]  (12.0, 18.0]
1  (2.0, 4.0]  (8.0, 15.0]   (7.0, 13.0]  (12.0, 18.0]
2  (4.0, 7.0]  (8.0, 15.0]  (13.0, 19.0]  (12.0, 18.0]
3  (4.0, 7.0]  (8.0, 15.0]   (7.0, 13.0]   (5.0, 12.0]
4  (4.0, 7.0]   (1.0, 8.0]   (7.0, 13.0]   (5.0, 12.0]

如果想要通过相同的 bin 处理所有列,请使用 DataFrame.stack对于MultiIndex Series,应用剪切并通过 Series.unstack reshape 回来:

newDF = pd.cut(df.stack(), 2, precision=0).unstack()
print (newDF)
              A             B             C             D
0  (10.0, 19.0]  (10.0, 19.0]  (10.0, 19.0]  (-0.0, 10.0]
1  (10.0, 19.0]  (10.0, 19.0]  (-0.0, 10.0]  (-0.0, 10.0]
2  (-0.0, 10.0]  (10.0, 19.0]  (-0.0, 10.0]  (-0.0, 10.0]
3  (-0.0, 10.0]  (-0.0, 10.0]  (10.0, 19.0]  (-0.0, 10.0]
4  (10.0, 19.0]  (10.0, 19.0]  (-0.0, 10.0]  (-0.0, 10.0]

关于python - 在所有数据帧列上应用不同 bin 大小的 binning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60566534/

相关文章:

python - 用pygame绘制对角椭圆

python - 如何计算 Python pandas 数据框的修改后移动平均线?

apache-spark - PySpark,决策树(Spark 2.0.0)

python - pandas 列的数据类型在通过应用传递给函数时更改为对象?

python - 将 DataFrame 中每列的值设置为第 90 个百分点

python - 将数据帧行与 python/pandas 成对比较(位置索引器超出范围)

python - 使用 Pandas 读取数据并将其设置为 DataFrame 的索引

python - 在函数参数中使用字符串从 Python 调用 Rust

Python 类型提示 - 方法返回当前类的列表

python - 行拆分后添加字典键和值?