Guga
Guga

Reputation: 349

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 column 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.

Upvotes: 2

Views: 2396

Answers (3)

piRSquared
piRSquared

Reputation: 294328

I thought this was interesting

df.reset_index().applymap('XXXX{}'.format).sum(1)

0    XXXX1XXXX15.1726XXXX0.138628
1    XXXX2XXXX15.1726XXXX0.147002
2    XXXX3XXXX15.1726XXXX0.155376
3    XXXX4XXXX15.1726XXXX0.163749
4    XXXX5XXXX15.1726XXXX0.172123
dtype: object

Upvotes: 0

Steven G
Steven G

Reputation: 17122

you can use apply

df['NewCol'] = df.apply(lambda x: "XXXX" + str(x.name) + "XXXX" + str(x.A) + "XXXX" + str(x.B), axis=1)

also, a bit shorter, from @Abdou

df['joined'] = df.apply(lambda x: 'XXXX'+'XXXX'.join(map(str,x)),axis=1) 

Upvotes: 6

milos.ai
milos.ai

Reputation: 3930

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()]

Upvotes: 1

Related Questions