1

Given a dataframe with multiple columns, whats the most pythonic way to combine them with their column headers into a new dataframe column. For example, given red, blue, and green, how do I add colors as a column.

   red  blue  green colors
0    1     2     dd      {'red':1, 'blue': 2, 'green': 'dd'}    
1    2     3     ee      {'red':2, 'blue': 3, 'green': 'ee'} 
2    3     4     ff      {'red':2, 'blue': 4, 'green': 'ff'} 

1 Answer 1

3

You can use to_dict() to create a list of dictionaries and then assign it back to df as a column

df['colors'] = df.to_dict("records")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.