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

前端 未结 3 1217
無奈伤痛
無奈伤痛 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:24

    Even I am with @DSM for using zfill. But I think using lamba makes it much cleaner and easy to read.

    In [1]: import pandas as pd
    
    In [2]: df = pd.DataFrame([45362.0, 75345.0, 346157.0, 572575.0], columns=['code_x'])
    
    In [3]: df.code_x.apply(lambda x: str(int(x)).zfill(6))
    Out[3]: 
    0    045362
    1    075345
    2    346157
    3    572575
    Name: code_x, dtype: object
    

    Note: We are converting a given value to int before converting to string to get rid of ".0" in results.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-26 21:50

    IIUC, you can use str.zfill which means you wouldn't have to special-case by length:

    In [16]: ser
    Out[16]: 
    0     45362
    1     75345
    2    346157
    3    572575
    dtype: float64
    
    In [17]: ser.astype(str).str.zfill(8)
    Out[17]: 
    0    045362.0
    1    075345.0
    2    346157.0
    3    572575.0
    dtype: object
    
    0 讨论(0)
提交回复
热议问题