Nickpick
Nickpick

Reputation: 6587

Python pandas: change one column conditional on another

How can I reverse the sign in the quantity column whenever the side column has a sell? All other values should not be changed. The following is simply not working, it has no effect.

df[df['side'] == 'Sell']['quantity'] = df[df['side'] == 'Sell']['quantity'] * -1

Upvotes: 5

Views: 896

Answers (1)

Alexander
Alexander

Reputation: 109526

Refer to the Pandas indexing documentation, and never use chain indexing per your example when setting values.

df.loc[df.side == 'Sell', 'quantity'] *= -1

Upvotes: 4

Related Questions