3

I have a dataframe like below.

df = pd.DataFrame([111111,123456,12345,234,12,987654],columns=['id'])

so if you look at the row 3,4,5 the length of the ids are less than 6

id
111111
123456
12345
234
12
987654

I want to convert it to below(Basically append zeroes in the front to make it a length of six)

id
111111
123456
012345
000234
000012
987654
  • Perhaps take a look at https://stackoverflow.com/questions/134934/display-number-with-leading-zeros – sfjac Jan 02 '19 at 02:41

3 Answers3

3

Using

df.id.astype(str).str.pad(6,'left','0')
0    111111
1    123456
2    012345
3    000234
4    000012
5    987654
Name: id, dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234
3

Try zfill, first convert integers to string dtype then use string accessor then zfill:

df['id'].astype(str).str.zfill(6)

Output:

0    111111
1    123456
2    012345
3    000234
4    000012
5    987654
Name: id, dtype: object
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

You have to change the datatype to string or else the initial zeroes will be trimmed. Below is my solution. Hope it helps

df = pd.DataFrame([111111,123456,12345,234,12,987654],columns=['id'])
df = df.astype(str)
df['id'] = df['id'].apply(lambda x: x if len(x)==6 else '0'*(6-len(x))+x)

df:
id
111111
123456
012345
000234
000012
987654
Bhanu Tez
  • 296
  • 2
  • 14