When I have data of quantity and buy and sell program, I want to get the cumulative quantity by adding a number when it is 'buy' and deducting a number when it is 'sell'. How can I do this in pandas? I know there is .cumsum() function to add it, but I don't know how to deduct it.
Asked
Active
Viewed 128 times
0
-
Can you add the data snippet as code rather than an image so that people have a [reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to work with – Sparrow0hawk Nov 03 '21 at 13:28
-
Try https://stackoverflow.com/a/49161189/874188 for a start – tripleee Nov 03 '21 at 13:29
1 Answers
0
You can flip the integer when selling:
df['quantity'].where(df['buy&sell'].eq('buy'), -df['quantity']).cumsum()

mozway
- 194,879
- 13
- 39
- 75