Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add column name at the end of each value of a column pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     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)

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading