Guga Guga - 28 days ago 14
Python Question

Create a string columns based on values of columns and index Pandas

I have the following dataframe:

A B
Tenor
1 15.1726 0.138628
2 15.1726 0.147002
3 15.1726 0.155376
4 15.1726 0.163749
5 15.1726 0.172123


I want to be able to create another colunmn that has a string by concatenating the previous columns, including the index. For instance, first row of this new columns would be: XXXX1XXXX15.1726XXXX0.138628

How can I do that in Pandas? If I try to use df[ColumnName] in the string formula Pandas will always bring the index, which will mess up my string.

Thanks,
Augusto

Answer

You can try something like this:

df['newColumn'] = [("XXXX"+str(id)+"XXXX" +str(entry.A) + "XXXX" +str(entry.B)) for id,entry in df.iterrows()]
Comments