Issue
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
Solution
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)
Answered By - richardec
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.