-1

I have a pandas Series of strings and I want to append this strings at the beginning of it with zeros.

for example I have this 123456 and I want to have this 00000123456. Not all the strings are equal size(length) and each string's size must be 11.

I tried this code:

x = [6, 7, 8, 9, 10]
for i in range(len(x)):
    if x[i] == df['ID'].str.len():
        df['ID'].join((11-i)*'0')

and getting this error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Can anyone help me?

Shaido
  • 27,497
  • 23
  • 70
  • 73
Okroshiashvili
  • 3,677
  • 2
  • 26
  • 40
  • 3
    Possible duplicate of [Nicest way to pad zeroes to string](https://stackoverflow.com/questions/339007/nicest-way-to-pad-zeroes-to-string) – Austin May 21 '18 at 07:41

2 Answers2

3

You can use str.zfill

Ex:

n = "123456"
print(n.zfill(11))

Output:

00000123456
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

In pandas, use str on your column and then zfill. Small example:

df = pd.DataFrame(['123456', '234567', '345678'], columns=['ID'])
df['ID'] = df['ID'].str.zfill(11)

Gives you:

             ID
0   00000123456
1   00000234567
2   00000345678
Shaido
  • 27,497
  • 23
  • 70
  • 73