I have the pandas dataframe below with 2 columns.
df = pd.DataFrame({'quantity':[15, 30, 35, 20], 'sign':[1,1,2,1]})
I want to apply a conditional statement and multiply the quantity
value in each row by -1 if the corresponding sign
value in that row is equal to 2. I don't want to create a new column. I just want to apply this to the quantity
column.
I have tried using .loc
and .apply(lamda x:)
, but I must not be applying them correctly. Any help is appreciated.
Use DataFrame.loc
with mask by Series.eq
for equality and multiple by scalar:
df = pd.DataFrame({'quantity':[15, 30, 35, 20], 'sign':[1,1,2,1]})
df.loc[df['sign'].eq(2), 'quantity'] *= - 1
print (df)
quantity sign
0 15 1
1 30 1
2 -35 2
3 20 1
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.