How To Only Do String Manupilation On Column Of Pandas That Have 4 Digits Or Less?
I have df that looks like this: numbers 0 111 1 22222 2 3423 I want to apply a 0 to the beginning of any 4digit number, how do I do this? New df should look like t
Solution 1:
Using rjust
df=df.astype(str)
df.loc[df.numbers.str.len()==4,'numbers']=df.numbers.str.rjust(5,'0')
df
Out[370]:
numbers
01111222222 03423
Solution 2:
pandas.Series.str.zfill
df = df.astype(str) # Making sure these are strings
mask = df.numbers.str.len() == 4
df.loc[mask, 'numbers'] = df.loc[mask, 'numbers'].str.zfill(5)
df
numbers
01111222222 03423
Post a Comment for "How To Only Do String Manupilation On Column Of Pandas That Have 4 Digits Or Less?"