pd.series.str.pad() returns NaNs

patients_clean.zip_code returns:

0      92390
1      61812
2      68467
3       7095
4      36303
5      32114

I want to pad it so that zip codes with missing ‘0’s on the left are fixed, so I apply this: patients_clean.zip_code.str.pad(width=5, side='left', fillchar='0')

However, this returned a series of NaNs can anyone explain this behaviour?

0     NaN
1     NaN
2     NaN
3     NaN
4     NaN
5     NaN

Answer

I think values are not strings, but integers, so need Series.astype:

print (patients_clean.zip_code.astype(str).str.pad(width=5, side='left', fillchar='0'))
0    92390
1    61812
2    68467
3    07095
4    36303
5    32114
Name: zip_code, dtype: object

Her working also same way Series.str.zfill:

print (patients_clean.zip_code.astype(str).str.zfill(5))
0    92390
1    61812
2    68467
3    07095
4    36303
5    32114
Name: zip_code, dtype: object

Leave a Reply

Your email address will not be published. Required fields are marked *