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

前端 未结 3 1246
無奈伤痛
無奈伤痛 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.

提交回复
热议问题