What is pandas syntax for lookup based on existing

2019-09-11 07:07发布

问题:

I'm trying to recreate a bit of a convoluted scenario, but I will do my best to explain it:

  1. Create a pandas df1 with two columns: 'Date' and 'Price' - done
  2. I add two new columns: 'rollmax' and 'rollmin', where the 'rollmax' is an 8 days rolling maximum and 'rollmin' is a rolling minimum. - done
  3. Now I need to create another column 'rollmax_date' that would get populated through a look up rule:

    • for the row n, go to the column 'Price' and parse through the values for the last 8 days and find the maximum, then get the value of the corresponding column 'Price' and put this value in the column 'rollingmax_date'.

    • the same logic for the 'rollingmin_date', but instead of rolling maximum date, we look for the rolling minimum date.

Now I need to find the previous 8 days max and min for the same rolling window of 8 days that I have already found.

I did the first two and tried the third one, but I'm getting wrong results. The code below gives me only dates where on the same row df["Price"] is the same as df['rollmax'], but it doesn't bring all the corresponding dates from 'Date' to 'rollmax_date'

df['rollmax_date'] = df.loc[(df["Price"] == df.rollmax), 'Date']

This is an image with steps for recreating the lookup