w3resource

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

Pandas: String and Regular Expression Exercise-4 with Solution

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.

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'] = list(map(lambda x: x.zfill(10), df['amount']))
print(df)

Sample Output:

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

Add leading zeros:
       amount
0  0000000010
1  0000000250
2  0000003000
3  0000040000
4  0000500000

Python Code Editor:


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

Previous: 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.
Next: Write a Pandas program to capitalize all the string values of specified columns of a given DataFrame.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Cache results with decorators

There is a great way to cache functions with decorators in Python. Caching will help save time and precious resources when there is an expensive function at hand.

Implementation is easy, just import lru_cache from functools library and decorate your function using @lru_cache.

from functools import lru_cache

@lru_cache(maxsize=None)
def fibo(a):
    if a <= 1:
        return a
    else:
        return fibo(a-1) + fibo(a-2)

for i in range(20):
    print(fibo(i), end="|")

print("\n\n", fibo.cache_info())

Output:

0|1|1|2|3|5|8|13|21|34|55|89|144|233|377|610|987|1597|2584|4181|

 CacheInfo(hits=36, misses=20, maxsize=None, currsize=20)