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

Time:03-26

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  

CodePudding user response:

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)

CodePudding user response:

or using numpy https://numpy.org/doc/stable/reference/generated/numpy.where.html

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

  • Related