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'])
Use the rjust() Function to Display a Number With Leading Zeros in Python. The rjust() function adds padding to the left side of a string. Padding, in simple terms, is the injection of non-informative characters to the left or the right side of a given string, which adds no additional value to the initial string.
Add leading zeros the string in python – zfill() function zfill() Function in Python pads string on the left with zeros to the required width.
For padding a string with leading zeros, we use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With