代码之家  ›  专栏  ›  技术社区  ›  rodrigo-silveira selftaught91

pandas将n列除以固定列

  •  0
  • rodrigo-silveira selftaught91  · 技术社区  · 6 年前

    给定这样的数据帧

       ImageId | Width | Height | lb0 | x0 | y0 | lb1 | x1 | y1 | lb2 | x2 | y2
    0  abc     | 200   | 500    | ijk | 4  | 8  | zyx | 15 | 16 | www | 23 | 42
    1  def     | 300   | 800    | ijk | 42 | 23 | zyx | 16 | 15 | www | 8  | 4
    2  ghi     | 700   | 400    | ijk | 9  | 16 | zyx | 17 | 24 | www | 43 | 109
    3  jkl     | 500   | 100    | ijk | 42 | 23 |     |    |    |     |    |
    ...
    

    问题:

    • 如何划分列 [x0, x1] 通过 [Width] [y0, y1] 通过 [Height] 是吗?

    我可以给所有的 x*

    df.iloc[:, 4::3] = SOME_SCALAR_VALUE
    

    但我想做的是

    df.iloc[:, 4::3] = df.iloc[:, 4::3] / df['Width']
    

    又回来了

    值错误:操作数不能与形状一起广播(62936,)(8,)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Scott Boston    6 年前

    使用 div 具有 axis=0 参数:

    df.iloc[:, 4::3].div(df['Width'], axis=0)
    

    输出:

             x0        x1        x2
    0  0.020000  0.075000  0.115000
    1  0.140000  0.053333  0.026667
    2  0.012857  0.024286  0.061429
    
        2
  •  0
  •   mccandar    6 年前

    这样就可以了

    df.iloc[:,4:3] = df.iloc[:,4:3].apply(lambda x: x/df['Width'],axis=0)