Home > Back-end >  Pandas: How to create a new column where values based on conditions column-wise
Pandas: How to create a new column where values based on conditions column-wise

Time:10-14

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?

CodePudding user response:

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
  • Related