代码之家  ›  专栏  ›  技术社区  ›  Peter Chen

基于容器创建列

  •  1
  • Peter Chen  · 技术社区  · 6 年前

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

    我想通过bins的min和max的平均值创建一个新列。

    # 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)
    

    因此,第2列=(bin最小值+bin最大值)/2。

    1 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    使用 GroupBy.transform 使用lambda函数返回 Series 与原版尺寸相同 DataFrame :

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

    或者用双倍 transform 具有 add div :

    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