Ad

Append String At The Beginning

- 1 answer

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?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad