How to drop multiple rows with datetime index?

Question:

I have the pandas data frame as below with a datetime index. The dataframe shows the data for the month of April and May. (The original dataframe has many more columns).

I want to remove all the rows for the month of May i.e. starting from index 2022-05-01 00:00:00 and ending at 2022-05-31 23:45:00. Currently, I am doing it by explicitly mentioning the index labels but I am sure that should be a more sophisticated way to do it without having to mention the index labels so that if the data changes and I want to remove the next month, I don’t have to hard code it. I would appreciate help with this.

Current Code:

start_remove = pd.to_datetime('2022-05-01 00:00:00')
end_remove = pd.to_datetime('2022-05-01 23:45:00')
df = df.loc[(df.index < start_remove) | (df.index > end_remove)]

Sample Dataset:

date                   Open      Close       High      Low 
...
2022-04-30 23:30:00     10         11.4          10.2        10.7    
2022-04-30 23:45:00     18         17.2          17.2        15.8    
2022-05-01 00:00:00     24         24            24.8        24.8  
2022-05-01 00:15:00     59         58            60          60.3 
2022-05-01 00:30:00     43.7       43.9          48          48  
...
...
2022-05-31 23:45:00     41.7       53.9          51          50  

Asked By: A Newbie

||

Answers:

Try this:

df[df.index.dt.month != 5]
Answered By: gtomer

you may want to include the year when choosing month, to avoid deleting same month from other year

# assumption: date field is an index 
# and is already converted to datetime using pd.to_datetime

df.drop(df.loc[df.index.strftime('%Y%m') == '202205'].index)

converting index to datetime

df.index=pd.to_datetime(df.index)
df
Answered By: Naveed
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.