'Pandas Method chaining: reassigning a column using df.assign()
I have a dataframe with stock returns in one column, strategy values in another & and another column called trades with boolean values (True, False).
My desire is to subtract a particular value (tc) from a cell with in the strategy column if the corresponding boolean is True otherwise the cell is left untouched.
This is my code:
data_1['strategy'][data_1['trades']]-= tc
which runs well. However I would have preferred to use the method of chaining so as to make my code compact.
data_1.assign(strategy = lambda x: x['strategy'][x['trades']]-= tc)
This code throws an error around the -= saying the
SyntaxError: invalid syntax
Solution 1:[1]
IIUC, you can mask it:
data_1['strategy'] = data_1['strategy'].mask(data_1['trades'], data_1['strategy']-tc)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
