Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']) 
like image 568
jgaw Avatar asked May 23 '14 18:05

jgaw


People also ask

How do I add a zero in front of a single digit in Python?

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.

How do you add leading zeros to a DataFrame in Python?

Add leading zeros the string in python – zfill() function zfill() Function in Python pads string on the left with zeros to the required width.

How do you add leading zeros to a string in Python?

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.


Video Answer


2 Answers

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)) 
like image 132
Rohit Avatar answered Oct 08 '22 07:10

Rohit


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

like image 26
Guangyang Li Avatar answered Oct 08 '22 07:10

Guangyang Li