如何使用涉及日期

时间:2018-06-09 12:00:41

标签: python pandas time-series slice logical-operators

我想了解在Pandas中使用时间序列进行切片,并且我正在研究在逻辑语句(合并和/或不是操作数)中组合涉及日期的可能性。

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

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日期对应的值。

有效。

有没有更优雅的方法来实现同样的目标?

2 个答案:

答案 0 :(得分:2)

首先使用pd.to_datetime转换为datetime。然后,您可以在loc声明中使用datetring:

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

答案 1 :(得分:1)

首先使用date_rangeunion创建已移除值的DatetimeIndex,然后仅选择具有原始索引的difference

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)]

如果只想使用dateindex也包含time s 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

你的解决方案应该是simlify:

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