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], 'Number':[1,12,123,1234,12345]})
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'] = df.Number.map("{:05d}".format) df
Alternatively, we could have used the zfill
function as follows:
df['Leading'] = df.Number.apply(lambda x: str(x).zfill(5)) df