Home > Enterprise >  add column name at the end of each value of a column pandas
add column name at the end of each value of a column pandas

Time:02-04

I have a pandas df, something like this:

     date  col1    col2    col3        col4
0  4-4-22   cat  ginger  gentle      placed
1  4-4-22   dog  golden    wild  not placed
2  4-4-22  fish   black  domest  not placed
3  4-4-22   dog   brown  gentle      placed

For the list of names of the columns that I give, I want each value of those columns to have the column name added in brackets at the end. For eg.

lst = ['col2', 'col4']

Desired output:

     date  col1           col2    col3               col4
0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
1  4-4-22   dog  golden (col2)    wild  not placed (col4)
2  4-4-22  fish   black (col2)  domest  not placed (col4)
3  4-4-22   dog   brown (col2)  gentle      placed (col4)

CodePudding user response:

Use add after ensuring that the columns are strings (with astype):

cols = ['col2', 'col4']

df[cols] = df[cols].astype(str).add([f' ({c})' for c in cols])

Output:

     date  col1           col2    col3               col4
0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
1  4-4-22   dog  golden (col2)    wild  not placed (col4)
2  4-4-22  fish   black (col2)  domest  not placed (col4)
3  4-4-22   dog   brown (col2)  gentle      placed (col4)

CodePudding user response:

I would use the Series attribute name :

property Series.name : Return the name of the Series.

lista = ["col2", "col4"]
​
df[lista] = df[lista].apply(lambda x: x   f" ({x.name})")

​ Output :

print(df)

     date  col1           col2    col3               col4
0  4-4-22   cat  ginger (col2)  gentle      placed (col4)
1  4-4-22   dog  golden (col2)    wild  not placed (col4)
2  4-4-22  fish   black (col2)  domest  not placed (col4)
3  4-4-22   dog   brown (col2)  gentle      placed (col4)
  • Related