w3resource

Pandas: Add leading zeros to the integer column in a pandas series and makes the length of the field to 8 digit


3. Add Leading Zeros to Integers

Write a Pandas program to add leading zeros to the integer column in a pandas series and makes the length of the field to 8 digit.

Sample Solution:

Python Code :

import pandas as pd
nums = {'amount': [10, 250, 3000, 40000, 500000]}
print("Original dataframe:")
df = pd.DataFrame(nums)
print(df)
print("\nAdd leading zeros:")
df['amount'] = df['amount'].apply(lambda x: '{0:0>8}'.format(x))
print(df)

Sample Output:

Original dataframe:
   amount
0      10
1     250
2    3000
3   40000
4  500000

Add leading zeros:
     amount
0  00000010
1  00000250
2  00003000
3  00040000
4  00500000

For more Practice: Solve these Related Problems:

  • Write a Pandas program to format an integer series by adding leading zeros so that each value becomes 8 digits long.
  • Write a Pandas program to convert an integer series into strings padded with zeros on the left to achieve a fixed length of 8.
  • Write a Pandas program to update an integer column by formatting each number with leading zeros and then verify the string length.
  • Write a Pandas program to transform a numeric series into a string series with 8-digit formatting including leading zeros.

Go to:


Previous: Write a Pandas program to remove whitespaces, left sided whitespaces and right sided whitespaces of the string values of a given pandas series.
Next: Write a Pandas program to add leading zeros to the character column in a pandas series and makes the length of the field to 8 digit.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.