problem to concatenate the index of a pandas series with a string

Viewed 32

I would like to have the index of row concanate to the a string in a dataframe column, like C-00000001 where C- is the string and 01 is the index format with 9 characters... i tried a lot of thing without solution...

df_complete['Code du client *']="C-"+ str(df_complete.index)
1 Answers

str(…) will give you a unique string, that will be broadcasted to all rows.

You need to use a vectorial transformation with astype:

df_complete['Code du client *'] = 'C-' + df_complete.index.astype(str)

If you have a range index and want to ensure 9 characters, use zfill:

'C-' + df_complete.index.astype(str).str.zfill(9)
Related