Guga Guga - 1 year ago 68
Python Question

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

I have the following dataframe:

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.


Answer Source

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()]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download