0

I habe the following dataframe:

          Cap
0          44
1       40017
2         123
3       13900
4        9122
      ...
317173  41012
317174  39055
317175   9055
317176    146
317177  74121

The values in column ['Cap'] should content 5 digits. The missing digits should be zeros:

          Cap
0       00044
1       40017
2       00123
3       13900
4       09122
      ...
317173  41012
317174  39055
317175  09055
317176  00146
317177  74121

I am new at programming. I created the following iterative process which works, but I am sure there have to be a more efficient way of doing this (in the original dataframe there are more columns).

for lab, row in df.iterrows():
   if len(str(df.loc[lab, 'Cap'])) == 1:
       df.loc[lab, 'Cap'] = '0000' + str(df.loc[lab, 'Cap'])
   elif len(str(df.loc[lab, 'Cap'])) == 2:
       df.loc[lab, 'Cap'] = '000' + str(df.loc[lab, 'Cap'])
   elif len(str(df.loc[lab, 'Cap'])) == 3:
       df.loc[lab, 'Cap'] = '00' + str(df.loc[lab, 'Cap'])
   elif len(str(df.loc[lab, 'Cap'])) == 4:
       df.loc[lab, 'Cap'] = '0' + str(df.loc[lab, 'Cap'])

Thank you.

Albert
  • 1
  • 1

0 Answers0