从随机日期时间熊猫列中选择一组连续日期

时间:2019-07-12 23:52:14

标签: python pandas data-science

我有一个pandas datetime列,其中的日期未排序。我想在此列中选择接下来的6个连续日期可用的所有日期,而中间没有任何丢失的日期。

我的数据看起来像这样,我已经在图像中标记了我想要的日期。

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试一下:

import pandas as pd
from datetime import timedelta

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

1-对日期进行排序

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

2-运行代码以选择日期

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

3-如果需要,请取消排序,以使数据框恢复到原始状态

df.sort_index(inplace=True)

enter image description here