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
>Solution :
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