-2

I'm a beginner in python. I'm using python 3.X in my windows 7 I have a pandas series. Currently it contains 1544252 records of 8 digit number of int64 type. Sample of last few records are given below

1544241    87526878
1544242    92480921
1544243    61479211
1544244    57572826
1544245    25527504
1544246    69477558
1544247    35477532
1544248    12475315
1544249    75480854
1544250    68527476
1544251    87480808

I need to add leading zeros in my series to make 8 digit number to 10 character long string. Here is my desired output.

    1544241    0087526878
    1544242    0092480921
    1544243    0061479211
    1544244    0057572826
    1544245    0025527504
    1544246    0069477558
    1544247    0035477532
    1544248    0012475315
    1544249    0075480854
    1544250    0068527476
    1544251    0087480808

Can you please suggest me how to do that in time efficient way?

Thanks in advance

Athul Soori
  • 91
  • 1
  • 8
emily jones
  • 23
  • 2
  • 5
  • 3
    _how to do that in time efficient way?_ What inefficient ways have you been trying? – B001ᛦ Jan 31 '18 at 11:15
  • Try the below link to know how to add leading zeros https://stackoverflow.com/questions/134934/display-number-with-leading-zeros – Athul Soori Jan 31 '18 at 11:21

6 Answers6

2

If you series is called s

'00'+s.astype(str)

works.

Flo Martin
  • 131
  • 6
0

Something like this ?

df['tendigits'] = df['eightdigits'].apply(lambda n: '00' + str(n))
arnaud
  • 3,293
  • 1
  • 10
  • 27
0
s = pd.Series(map(lambda x: '%010d' %x, s))

where s is your series.

talz
  • 1,004
  • 9
  • 22
0

You can use the zfill function which left-pads with leading zeros and takes as an argument the witdh of the desired output.

If s is your series, you can do:

s.apply(lambda x : x.zfill(10))
greg hor
  • 682
  • 6
  • 17
0

This is a vectorised way:

import pandas as pd

df = pd.DataFrame([[1544241, 87526878],
                   [1544242, 92480921]],
                  columns=['A', 'B'])

df.B = df.B.astype(str).str.zfill(10)

#          A           B
# 0  1544241  0087526878
# 1  1544242  0092480921
jpp
  • 159,742
  • 34
  • 281
  • 339
0

There is a builtin function for padding in pandas,

and you must cast to string before:

s.astype(str).str.pad(width=10, side='left', fillchar='0')

I tested it and it works.

ivankeller
  • 1,923
  • 1
  • 19
  • 20