【问题标题】:Create columns based on bins基于 bin 创建列
【发布时间】:2018-10-24 05:08:07
【问题描述】:

我有一个数据:

# dt
Column1     
      1
      2
      3
      4
      5
      6
      7
      8
      9

我想通过 bin 的最小值和最大值的平均值创建一个新列。

# dt
Column1    Column2
      1          2
      2          2
      3          2
      4          5
      5          5
      6          5
      7          8
      8          8
      9          8

pd.qcut(dt['Column1'], 3)

所以 column2 = (bin 的最小值 + bin 的最大值)/2。

【问题讨论】:

    标签: python pandas data-manipulation


    【解决方案1】:

    使用 GroupBy.transform 和 lambda 函数返回 Series 与原始 DataFrame 大小相同:

    dt['Column2'] = (dt.groupby(pd.qcut(dt['Column1'], 3))['Column1']
                       .transform(lambda x: x.max() + x.min()) / 2)
    

    或将transformadddiv 一起使用:

    g = dt.groupby(pd.qcut(dt['Column1'], 3))
    dt['Column2'] = g['Column1'].transform('max').add(g['Column1'].transform('min')).div(2)
    print (dt)
       Column1  Column2
    0        1      2.0
    1        2      2.0
    2        3      2.0
    3        4      5.0
    4        5      5.0
    5        6      5.0
    6        7      8.0
    7        8      8.0
    8        9      8.0
    

    编辑:

    cols = ['Column1']
    for col in cols:
        dt[f'New {col}'] = (dt.groupby(pd.qcut(dt[col], 3))[col]
                           .transform(lambda x: x.max() + x.min()) / 2)
    print (dt)
       Column1  New Column1
    0        1          2.0
    1        2          2.0
    2        3          2.0
    3        4          5.0
    4        5          5.0
    5        6          5.0
    6        7          8.0
    7        8          8.0
    8        9          8.0
    

    【讨论】:

    • 如果列多,不输入怎么生成多次?具体来说,原来的新列名为Old column_B
    • @PeterChen - 你觉得像编辑过的答案吗?处理列在列表cols
    • 我在此使用了您的代码:for col in cols: dt[f'New {col}'] = dt.clip(dt.quantile(0.25) - 1.5*IQR, dt.quantile(0.75) + 1.5*IQR, axis = 1)[col],但它不起作用。也许我不能用这个?
    • @PeterChen - 我用dt = pd.DataFrame({'Column1': {0: 1, 1: 20, 2: 3, 3: 4, 4: 10, 5: 6, 6: 7, 7: 8, 8: 9}, 'aaa': {0: 4, 1: 7, 2: 8, 3: 2, 4: 1, 5: 30, 6: 1, 7: 6, 8: 3}})测试了它
    • 然后IQR = 0.2 cols = dt.columns for col in cols: dt[f'New {col}'] = dt.clip(dt.quantile(0.25) - 1.5*IQR, dt.quantile(0.75) + 1.5*IQR, axis = 1)[col]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2020-12-14
    • 1970-01-01
    • 2020-10-07
    • 2021-12-27
    相关资源
    最近更新 更多