Pandas extract numbers from column into new columns

后端 未结 5 2343
谎友^
谎友^ 2020-12-21 05:51

I currently have this df where the rect column is all strings. I need to extract the x, y, w and h from it into separate columns. The dataset is very large so I need an effi

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 06:07

    Inline

    Produce a copy

    df.assign(**dict(zip('xywh', df.rect.str.findall('\d+').str)))
    
                              rect    x    y    w    h
    0    120  168  260  120
    1    120  168  260  120
    2    120  168  260  120
    3    120  168  260  120
    4    120  168  260  120
    

    Or just reassign to df

    df = df.assign(**dict(zip('xywh', df.rect.str.findall('\d+').str)))
    
    df
    
                              rect    x    y    w    h
    0    120  168  260  120
    1    120  168  260  120
    2    120  168  260  120
    3    120  168  260  120
    4    120  168  260  120
    

    Inplace

    Modify existing df

    df[[*'xywh']] = pd.DataFrame(df.rect.str.findall('\d+').tolist())
    
    df
    
                              rect    x    y    w    h
    0    120  168  260  120
    1    120  168  260  120
    2    120  168  260  120
    3    120  168  260  120
    4    120  168  260  120
    

提交回复
热议问题