Add Leading Zeros to Strings in Pandas Dataframe
I have a pandas data frame where the first 3 columns are strings:
ID text1 text 2
0 2345656 blah blah
1 3456 blah blah
2 541304 blah blah
3 201306 hi blah
4 12313201308 hello blah
I want to add leading zeros to the ID:
ID text1 text 2
0 000000002345656 blah blah
1 000000000003456 blah blah
2 000000000541304 blah blah
3 000000000201306 hi blah
4 000012313201308 hello blah
I have tried:
df['ID'] = df.ID.zfill(15)
df['ID'] = '{0:0>15}'.format(df['ID'])
Try:
df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))
or even
df['ID'] = df['ID'].apply(lambda x: x.zfill(15))
str
attribute contains most of the methods in string.
df['ID'] = df['ID'].str.zfill(15)
See more: http://pandas.pydata.org/pandas-docs/stable/text.html
It can be achieved with a single line while initialization. Just use converters argument.
df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})
so you'll reduce the code length by half :)
PS: read_csv have this argument as well.