import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex'],'ID':[1,2,3],
'MATH':[30,40,50],'ENGLISH':[20,30,40]}
df = pd.DataFrame(data=my_dict)
df['MATH']=df['MATH'].astype(str) # to string dtype
#print(df.MATH.str.zfill(3))
df['MATH']=df.MATH.str.zfill(3)
print(df)
Output
NAME ID MATH ENGLISH
0 Ravi 1 030 20
1 Raju 2 040 30
2 Alex 3 050 40
my_dict={'NAME':['Ravi','Raju','Alex','King','Queen'],'ID':[1,2,3,4,5],
'MATH':[-3,-40,5,'abc',6000],'ENGLISH':[20,30,40,50,10]}
df = pd.DataFrame(data=my_dict)
df['MATH']=df['MATH'].astype(str)
df['MATH']=df.MATH.str.zfill(3)
print(df)
Output
NAME ID MATH ENGLISH
0 Ravi 1 -03 20
1 Raju 2 -40 30
2 Alex 3 005 40
3 King 4 abc 50
4 Queen 5 6000 10
The `str.zfill()` method can be used to ensure consistent numeric formatting, such as ID codes or product numbers.
import pandas as pd
data = {'Product': ['A', 'B', 'C'], 'Code': [7, 58, 105]}
df = pd.DataFrame(data)
df['Code'] = df['Code'].astype(str).str.zfill(5)
print(df)
Output
Product Code
0 A 00007
1 B 00058
2 C 00105
If your column contains a mix of integers, strings, or special characters, `zfill()` can still apply padding without affecting non-numeric data.
data = {'Category': ['alpha', 'beta', 'gamma'], 'ID': [5, 'x12', 'abc']}
df = pd.DataFrame(data)
df['ID'] = df['ID'].astype(str).str.zfill(4)
print(df) Output
Category ID
0 alpha 0005
1 beta 0x12
2 gamma 0abc
We can apply `zfill()` to alphanumeric codes, ensuring uniform padding for better sorting and display.
codes = pd.Series(['A1', 'B12', 'C3'])
padded_codes = codes.str.zfill(4)
print(padded_codes)
Output
0 00A1
1 0B12
2 00C3
dtype: object
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.