Ahamed Moosa
Ahamed Moosa

Reputation: 1445

Conditional Calculation of Pandas Dataframe columns

I have a pandas dataframe which reads

Category  Sales  
A           10
B           20

I wanna do a conditional creation of new column target

And I want my target df to look like

Category  Sales  Target 
A           10    5
B           20   10

I used the below code and it threw an error

if(df['Category']=='A'):
    df['Target']=df['Sales']-5
else:
    df['Target']=df['Sales']-10

Upvotes: 1

Views: 3573

Answers (1)

jezrael
jezrael

Reputation: 862781

Use vectorized numpy.where:

df['Target']= np.where(df['Category']=='A', df['Sales'] - 5, df['Sales'] - 10)
print (df)
  Category  Sales  Target
0        A     10       5
1        B     20      10

Upvotes: 5

Related Questions