Add leading zeros in Python pandas (preceding zeros in data frame)

In this Tutorial we will learn how to add Leading Zeros or preceding zeros in data frame in python pandas with an example. We will be filling the integer or string with preceding zeros till the desired length is obtained.

Objective: 

add leading zeros in python

Lets look how to do it with an example.

 

ADD leading Zeros in python to the Numeric column:

Create a simple DataFrame:

# create dataframe

import pandas as pd
d = {'Col1' : [1,200,3000,40000]}
df=pd.DataFrame(d)
print df

Which results in a dataframe as shown below.

Col1
1
200
3000
40000

Add the leading zeros to numeric column in Python pandas

## Add leading zeros to the integer column in Python

df['Col1']=df['Col1'].apply(lambda x: '{0:0>10}'.format(x))
print df

We will be taking a column of a dataframe Col1 and applying a format which adds preceding zeros and makes the length of the field to 10 digit as shown above so the output will be

Col1
0000000001
0000000200
0000003000
0000040000

 

 

ADD leading Zeros in python pandas to the character column:

Create a simple dataframe with character columns:

# create dataframe

import pandas as pd
d = {'Col1' : ["1","200","3000","40000"]}
df=pd.DataFrame(d)
print df

Which results in a dataframe as shown below.

Col1
1
200
3000
40000

Add the leading zeros to character column in Python pandas

## Add leading zeros to the character column in Python

df['Col1']= map(lambda x: x.zfill(10), df['Col1'])
print df

with the help of zfill() function we will be filling the character column with leading zeros so resultant column will be

Col1
0000000001
0000000200
0000003000
0000040000

 

previous add leading zeros in python dataframe pandas                                                                                                                next add leading zeros in python dataframe pandas