Pandas: How to create a new column where values based on conditions column-wise

Question:

Say I have a column in my df. There are only three distinct values: Apple, banana and kiwi

Category 
Apple 
Apple 
Apple 
Banana
Kiwi 
Banana
Banana
Banana

And I would like to insert a new column of their corresponding color

Category Color
Apple Red
Banana yellow
Kiwi green

How can i create such a column?

Asked By: user16971617

||

Answers:

df['Color'] = ['Red', 'yellow', 'green']

To accommodate the edit:

df['Color'] = df['Category'].map({'Apple': 'Red', 'Banana': 'yellow', 'Kiwi': 'green'})
    Category    Color
0   Apple   Red
1   Apple   Red
2   Apple   Red
3   Banana  yellow
4   Kiwi    green
5   Banana  yellow
6   Banana  yellow
7   Banana  yellow
Answered By: John Stud
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.