How do I select data between different weeks and group them to store the sliced DataFrame according week in an array?,

Viewed 42

I want to get weekly high low close for the dataFrame below So I want to slice the DataFrame according to weeks and store in an array

  • Date Open High Low Close

  • 01-08-2019 | 97.85 | 98.45 | 96.40 97.25


  • 02-08-2019 | 97.15 | 98.95 | 96.75 98.15

  • 05-08-2019 | 98.30 | 98.70 | 94.30 95.65

  • 06-08-2019 | 95.75 | 97.75 | 95.20 97.05

  • 07-08-2019 | 96.80 | 97.70 | 96.05 96.90

  • 08-08-2019 | 97.40 | 98.90 | 96.55 97.40

  • 09-08-2019 | 97.20 | 98.10 | 96.65 97.30

  • 12-08-2019 | 97.20 | 97.25 | 93.40 93.75

  • 13-08-2019 | 93.70 | 96.60 | 93.15 96.35

  • 14-08-2019 | 95.85 | 96.40 | 94.00 94.45

August 01-08-2019 ,02-08-2019 is one week. August 05-08-2019, 06-08-2019, 07-08-2019, 08-08-2019, 09-08-2019 is second week I want data in dataframe should be grouped according to week.

1 Answers

To change the frequency of a time-based dataframe, you can use the resample method. The following code should work:

(
    df
    .assign(Date=lambda x: pd.to_datetime(x['Date'], dayfirst=True)
    .set_index('Date')
    .asfreq('D')
    .resample('W')
    .agg({
       'High': 'max',
       'Low': 'min',
       'Open': lambda x: x.dropna().iloc[0],
       'Close': lambda x: x.dropna().iloc[-1]
    })
)
Related