Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fill DataFrame Column depends on condition

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading