Bill Software Engineer
Bill Software Engineer

Reputation: 7782

In Pandas, how do I drop rows based on date index not in date range?

I have some data in a dataframe with an date index:

              SP500_movement  SP500_movement_5days  SP500_movement_21days
Date                                                                   
2021-03-08             NaN                   NaN                    NaN
2021-03-09        0.013957                   NaN                    NaN
2021-03-10        0.005994                   NaN                    NaN

How do I drop all the rows that's not in the date range specified? This is what I have tried.

        data = data.drop(data.loc[data.index < startDate])
        data = data.drop(data.loc[data.index > endDate])

The date range are in startDate, endDate, which are both in datetime format.

This is the error I get:

KeyError: "['SP500_movement' 'SP500_movement_5days' 'SP500_movement_21days'] not found in axis"

Upvotes: 0

Views: 837

Answers (1)

BENY
BENY

Reputation: 323226

Let us do this

data = data.loc[(data.index >= startDate) & (data.index <= endDate)])

Or if you index is data time format

data = data.loc[startDate : endDate,:]

Upvotes: 1

Related Questions