Search code examples
pythonpandasdataframetrading

Python pandas: how to change categorical values in between 2 different categories


Hi everyone I am working on stock market data and I was wondering how to change the pandas data frame as below

From: Signal To: Signal_new
Buy Buy
Buy Hold
Buy Hold
Sell Sell
Sell Hold
Sell Hold
Sell Hold
Buy Buy

thanks in advance!


Solution

  • Try this:

    df[df['Signal'] == df['Signal'].shift(1)] = 'Hold'
    

    Output:

    >>> df
      Signal
    0    Buy
    1   Hold
    2   Hold
    3   Sell
    4   Hold
    5   Hold
    6   Hold
    7    Buy