dark_shadow
dark_shadow

Reputation: 43

Select group of consecutive dates from random datetime pandas column

I have a pandas datetime column where dates are not sorted. I want to select all the dates for which the next 6 consecutive dates are available in the column without any missing day in between.

My data looks something like this and I have marked the date I want in the image.

enter image description here

Upvotes: 1

Views: 162

Answers (1)

Gustavo Gradvohl
Gustavo Gradvohl

Reputation: 712

Try this:

import pandas as pd
from datetime import timedelta

df  = pd.read_excel(r'C:\Users\me\Desktop\Sovrflw_data.xlsx')
df

1 - Sort the dates

df.sort_values(by='dates', inplace=True)

2- run the code to select the dates

df[df['dates'] - df['dates'].shift(-6) == timedelta(-6)]

3 - If needed undo the sort so the dataframe goes back to the original state

df.sort_index(inplace=True)

enter image description here

Upvotes: 2

Related Questions