1

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ahamed Moosa
  • 1,395
  • 7
  • 16
  • 30

1 Answers1

5

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks @jezrael , actually I tried the same approach. But somehow I messed up with the syntax. Again thanks for helping out – Ahamed Moosa May 23 '18 at 09:05