str.zfill()


Prepending string with '0'
Returns string with filled 0

If we have integer column then we have to first change the object to string dtype by using astype().
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

Handling special chars , negative numbers and big numbers

Here we have negative number, single negative number, string and more than 3 char numbers. Check the output
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
Pandas contains() Converting char case split()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer