[SOLVED] How to use where conditon based on string values in a pandas dataframe?


How do I use multiple conditions to correct values in my dataframe

I want to change

  • Apple = Fruit
  • Potato = Veg

My data frame is like this

      Item      Category
      Apple     Freshco
      Potato    Sobeys
      Orange    Fruit
      Banana    Fruit

I want to change the two categories so the dataframe is like this

      Item      Categroy
      Apple     Fruit
      Potato    Veg
      Orange    Fruit
      Banana    Fruit  


Use .loc:

df.loc[df['Item'] == 'Apple', 'Category'] = 'Fruit'
df.loc[df['Item'] == 'Potato', 'Category'] = 'Veg'


>>> df
     Item Category
0   Apple    Fruit
1  Potato      Veg
2  Orange    Fruit
3  Banana    Fruit

More dynamic version:

reps = {
    'Apple': 'Fruit',
    'Potato': 'Veg',
df.loc[df['Item'].isin(reps), 'Category'] = df['Item'].replace(reps)

Answered By – richardec

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *