Pandas - Add leading “0” to string values so all values are equal len

前端 未结 3 1247
無奈伤痛
無奈伤痛 2021-01-26 21:00

I have a column, code_x. I converted it to .astype(str). Some example values are 45362.0, 75345.0, 346157.0, 572575.0. I would like them a

3条回答
  •  心在旅途
    2021-01-26 21:44

    You can use the Series.str.rjust method to right justify the string values and use 8 as the length and 0 as fill value. Example -

    df3['code_x'] = df3['code_x'].astype(str).str.rjust(8,'0')
    

    Demo -

    In [65]: df
    Out[65]:
            A
    0    blah
    1  supbla
    2       a
    
    In [69]: df['A'].str.rjust(6,'0')
    Out[69]:
    0    00blah
    1    supbla
    2    00000a
    Name: A, dtype: object
    

提交回复
热议问题