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

Viewed 38

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  
2 Answers

Use .loc:

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

Output:

>>> 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)

Or using numpy.select:

np.select([df['Item'] == 'Apple', df['Item'] == 'Potato'], ['Fruit', 'Veg'], df['Category'])

Or, using a dict:

mapping = {
    'Apple': 'Fruit',
    'Potato': 'Veg',
}
df['Category'] = np.select([df['Item'] == k for k in mapping.keys()], [v for v in mapping.values()], df['Category'])
Related