Predictive Hacks

Leading Zeros in Python

Assume that you are dealing with SKU numbers/codes and you want all of them to have the same number of digits. Then you can fill the SKU numbers with leading zeros. Let’s see how we can do it in Python using an example with a Pandas data frame.

import pandas as pd

# create a pandas data frame
df = pd.DataFrame({'ID':[1,2,3,4,5],

Let’s say that we want all the numbers to be of 5 digits. As a result, we need to add some leading zeros, depending on the input size. We can work with the f-string and the pandas series as follows.

df['Leading'] ="{:05d}".format)


Alternatively, we could have used the zfill function as follows:

df['Leading'] = df.Number.apply(lambda x: str(x).zfill(5))

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s