'Slice DataFrame using Dates from a List and its offset as a range for slicing in a for loop

This my DataFrame df with calendar days frequency and DateTime Object as Index. This data starts from 1989-01-03 till present day:

                      Price
       1989-01-03   30.620064
       1989-01-04   30.540062
       1989-01-05   30.590061
       1989-01-06   30.600063
       1989-01-07   NaN
       1989-01-08   NaN
       1989-01-09   30.610062
       1989-01-10   30.590061
       1989-01-11   30.660061
       1989-01-12   30.660061

Here is my df.index.values:

array(['1989-01-03T00:00:00.000000000', '1989-01-04T00:00:00.000000000',
   '1989-01-05T00:00:00.000000000', ...,
   '2017-06-24T00:00:00.000000000', '2017-06-25T00:00:00.000000000',
   '2017-06-26T00:00:00.000000000'], dtype='datetime64[ns]')

I have a List of Dates :

[Timestamp('1989-02-01 00:00:00'),Timestamp('1989-03-01 00:00:00'),Timestamp('1989-04-01 00:00:00'),Timestamp('1989-05-01 00:00:00'),Timestamp('1989-06-01 00:00:00'),Timestamp('1989-07-01 00:00:00'),Timestamp('1989-08-01 00:00:00'),Timestamp('1989-09-01 00:00:00'),Timestamp('1989-10-01 00:00:00')]

I want to slice my df on for every dates in the Dates List such that I get data between Dates-100 and Dates(Calendar Days)

 for m in Dates:
     gg = df.iloc[(m-DateOffset(days=100)) : m]

I am getting this error:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.datetimes.DatetimeIndex'> with these indexers [1988-10-24] of <class 'datetime.date'>

Can someone help me with this error? and suggest a better way of doing this ?



Solution 1:[1]

I think I have found my error.

To get this working I should be using

gg = df.loc[(m-DateOffset(days=100)) : m]

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 jtlz2