Add Leading Zeros to Strings in Pandas Dataframe

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.


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))