Home > OS >  How to transform integer to string with certain character length in pandas
How to transform integer to string with certain character length in pandas

Time:04-07

Here's my dataset (integer value)

d
6
17
345

Here's what I want (string value)

d
0006
0017
0345

CodePudding user response:

You can use apply with Python format function in this case:

df['d'].apply('{:04d}'.format)
# or
# df['d'].apply(lambda x: f'{x:04d}')

CodePudding user response:

You could use str.zfill to prepending "0"s:

df['d'] = df['d'].astype(str).str.zfill(4)

Output:

      d
0  0006
1  0017
2  0345

CodePudding user response:

Let us try

df['d'].astype(str).str.pad(width=4, side='left', fillchar='0')
Out[226]: 
0    0006
1    0017
2    0345
Name: d, dtype: object
  • Related