Search code examples
pythonpandasmaxmin

Cumulative max/min based on criteria in separate column pandas


i want to check to see if there's a lower price than the current price among future dates. i've been able to do it for one stock at a time (DIS below is how i want it to look), but when i have two stocks, i can only return the min of the lower priced stock (DIS). i need each min to be relative to it's stock.

data['min'] = data['current_price'].iloc[::-1].cummin()[::-1]

    Symbols Date    current_price   min
0   AMZN    2020-07-01  2,754.00    112.00
2   AMZN    2020-07-02  2,871.10    112.00
4   AMZN    2020-07-06  2,930.00    112.00
6   AMZN    2020-07-07  2,990.00    112.00
8   AMZN    2020-07-08  3,012.43    112.00
10  AMZN    2020-07-09  3,074.00    112.00
12  AMZN    2020-07-10  3,135.70    112.00
14  AMZN    2020-07-13  3,068.39    112.00
1   DIS     2020-07-01    112.29    112.00
3   DIS     2020-07-02    112.00    112.00
5   DIS     2020-07-06    112.90    112.61
7   DIS     2020-07-07    112.61    112.61
9   DIS     2020-07-08    112.81    112.81
11  DIS     2020-07-09    115.38    115.38
13  DIS     2020-07-10    116.21    115.89
15  DIS     2020-07-13    115.89    115.89

Solution

  • You're almost there. Just add groupby and apply the same transformation that you're already doing in your post:

    data['min'] = data.groupby('Symbols')['current_price'].apply(
        lambda x: x[::-1].cummin()[::-1])
    
    print(data)
    
       Symbols        Date current_price       min
    0     AMZN  2020-07-01      2,754.00  2,754.00
    2     AMZN  2020-07-02      2,871.10  2,871.10
    4     AMZN  2020-07-06      2,930.00  2,930.00
    6     AMZN  2020-07-07      2,990.00  2,990.00
    8     AMZN  2020-07-08      3,012.43  3,012.43
    10    AMZN  2020-07-09      3,074.00  3,068.39
    12    AMZN  2020-07-10      3,135.70  3,068.39
    14    AMZN  2020-07-13      3,068.39  3,068.39
    1      DIS  2020-07-01        112.29    112.00
    3      DIS  2020-07-02        112.00    112.00
    5      DIS  2020-07-06        112.90    112.61
    7      DIS  2020-07-07        112.61    112.61
    9      DIS  2020-07-08        112.81    112.81
    11     DIS  2020-07-09        115.38    115.38
    13     DIS  2020-07-10        116.21    115.89
    15     DIS  2020-07-13        115.89    115.89
    ​```