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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.