Fill DataFrame Column depends on condition

Question:

I have the following DataFrame:

Fruit Color
Apple
Orange
Pear
Peach

How can I fill the second column that depends on the ‘Fruit’ column value?

For instance, if the fruit is ‘Apple’, then the second column should be ‘Red’, if the fruit is Orange, then the color should be ‘Orange’ and so on.

I have tried to use If statment, but it doesnt work.

import pandas as pd

d = {'Fruit': ['Apple', 'Orange', 'Pear', 'Peach'], 'Color': ['','','','']}
df = pd.DataFrame(data=d)
df
Asked By: Aragorn64

||

Answers:

(pd.DataFrame()
 .assign(fruit=['Apple', 'Orange', 'Pear', 'Peach'])
 .assign(color=lambda x: np.select([x.fruit == 'Apple',
                                    x.fruit == 'Orange',
                                    x.fruit == 'Pear',
                                    x.fruit == 'Peach'],
                                   ['Green',
                                    'Orange',
                                    'Dark green',
                                    'Pink'],
                                    default='blue')
        )                                                           
)
Answered By: William Rosenbaum

you could use apply and a map

import pandas as pd

d = {'Fruit': ['Apple', 'Orange', 'Pear', 'Peach'], 'Color': ['','','','']}
df = pd.DataFrame(data=d)

mapa = {'Apple':'red', 'Orange':'orange', 'Pear':'green', 'Peach':'light-orange'}
df.Color = df.Fruit.apply(lambda x: mapa[x])
df
Answered By: Lucas M. Uriarte

You can simply use pandas.Series.map :

dico = {'Apple': 'Red', 'Orange': 'Orange', 'Pear': 'Green', 'Peach': 'Rose'}

df['Color'] = df['Fruit'].map(dico)
# Output :
print(df)

    Fruit   Color
0   Apple     Red
1  Orange  Orange
2    Pear   Green
3   Peach    Rose
Answered By: abokey
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.