user13074756
user13074756

Reputation: 413

Add new column values based on other 2 column values in Pandas, Python

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

Answers (3)

Samir Hinojosa
Samir Hinojosa

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

Riccardo Bucco
Riccardo Bucco

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

Anurag Dabas
Anurag Dabas

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

Related Questions