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
CodePudding user response:
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
CodePudding user response:
(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')
)
)
CodePudding user response:
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