Reputation: 413
I have the below code
import pandas as pd
df = pd.DataFrame({
'name':
['apple','banana','lemon','apple','apple'],
'price':
[2,3,7,21,11],
'stock':
['Yes','No','No','No','Yes']
})
The dataframe looks like this
name price stock
0 apple 2 Yes
1 banana 3 No
2 lemon 7 No
3 apple 21 No
4 apple 11 Yes
I need to add new column, 'STATUS' to the same df, based on the values in two other columns. If name is apple and if stock is Yes, then status should be "GOLD" If name is apple and if stock is No, then status should be "Bronze" If name is banana or lemon and if stock is No, then status should be "Silver"
How do I go about this?
I can add a new column based on one column but how is it possible with 2?
Upvotes: 0
Views: 87
Reputation: 825
You can try with the code below
df["status"] = None
df.loc[(df["name"] == "apple") & (df["stock"] == "Yes"), "status"] = "Gold"
df
name price stock status
0 apple 2 Yes Gold
1 banana 3 No None
2 lemon 7 No None
3 apple 21 No None
4 apple 11 Yes Gold
Upvotes: 0
Reputation: 15384
Here is a possible solution:
df['STATUS'] = None
df.loc[(df['name'] == 'apple') & (df['stock'] == 'Yes'), 'STATUS'] = 'GOLD'
df.loc[(df['name'] == 'apple') & (df['stock'] == 'No'), 'STATUS'] = 'Bronze'
df.loc[(df['name'].isin(('banana', 'lemon'))) & (df['stock'] == 'No'), 'STATUS'] = 'Silver'
Upvotes: 2
Reputation: 24322
Try via np.select()
:
import numpy as np
conditions=[
(df['name']=='apple') & (df['stock']=='Yes'),
(df['name']=='apple') & (df['stock']=='No'),
(df['name'].isin(['banana','lemon'])) & (df['stock']=='No')
]
labels=['Gold','Bronze','Silver']
Finally:
df['STATUS']=np.select(conditions,labels,default=np.nan)
Upvotes: 1