-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
  • 25,575
  • 21
  • 68
  • 72
Okroshiashvili
  • 3,203
  • 1
  • 24
  • 35
  • 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
  • 78,594
  • 17
  • 67
  • 103
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
  • 25,575
  • 21
  • 68
  • 72