如何使用涉及日期的逻辑表达式对 Pandas 时间序列进行切片

How to slice a Pandas Time Series using a logical expression involving dates

我想了解 Pandas 中的时间序列切片,我正在研究在涉及日期的逻辑语句(组合 and , or, not 操作数)条件中组合的可能性。

所以这是一个可重现的例子:

HAO_10
Date         Price
2018-01-02  30.240000
2018-01-03  30.629999
2018-01-04  30.860001
2018-01-05  31.010000
2018-01-08  31.389999
2018-01-09  31.309999
2018-01-10  31.400000
2018-01-11  31.580000
2018-01-12  31.680000
2018-01-16  31.200001

HAO_10.iloc[((HAO_10.index < datetime.strptime('2018-01-04', '%Y-%m-%d')) | 

             ((HAO_10.index > datetime.strptime('2018-01-08', '%Y-%m-%d')) & 
        (HAO_10.index  != datetime.strptime('2018-01-12', '%Y-%m-%d')))), ]

这是尝试切出与 2018-01-04 之前和 2018-01-08 之后的日期对应的值,而不是与 2018-01-12 日期对应的值。

有效。

有没有更优雅的方法来完成同样的事情?

首先使用 pd.to_datetime 转换为日期时间。然后,您可以在 loc 语句中使用日期字符串:

df['Date'] = pd.to_datetime(df['Date'])

# This says: find where date is not between your range and not equal to 01-12
df.loc[(~df['Date'].between('2018-01-04','2018-01-08')) & (df['Date'] != '2018-01-12')]

        Date      Price
0 2018-01-02  30.240000
1 2018-01-03  30.629999
5 2018-01-09  31.309999
6 2018-01-10  31.400000
7 2018-01-11  31.580000
9 2018-01-16  31.200001

首先使用 date_range and union, then select only difference 和原始索引创建 DatetimeIndex 个删除的值:

idx = pd.date_range('2018-01-04','2018-01-08').union(['2018-01-12'])
df = HAO_10.loc[HAO_10.index.difference(idx)]
#another similar solutions
#df = HAO_10.drop(idx, errors='ignore')
#df = HAO_10[~HAO_10.index.isin(idx)]

如果只想与 dates 一起工作并且 index 也包含 times floor 是你的朋友:

df = HAO_10.loc[HAO_10.index.floor('d').difference(idx)]
#another similar solutions
#df = HAO_10[~HAO_10.index.floor('d').isin(idx)]

print (df)
                Price
2018-01-02  30.240000
2018-01-03  30.629999
2018-01-09  31.309999
2018-01-10  31.400000
2018-01-11  31.580000
2018-01-16  31.200001

您的解决方案应该简化为:

df = HAO_10[((HAO_10.index < '2018-01-04') | ((HAO_10.index > '2018-01-08') & 
                  (HAO_10.index  != '2018-01-12')))]