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

 ̄綄美尐妖づ 提交于 2019-12-24 00:33:22

问题


I want to understand slicing with timeseries in Pandas and I am looking at the possibility of combining in a logical statement (combining and , or, not operands) conditions involving dates.

So this is a reproducible example:

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

This is an attempt to slice out values corresponding to dates before 2018-01-04 and after 2018-01-08 but not the value corresponding to the date 2018-01-12.

It works.

Is there a more elegant way to accomplish the same?


回答1:


Create DatetimeIndex of removed values first with date_range and union, then select only difference with original index:

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

If want working with dates only and index contains also times floor is your friend:

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

Your solution should be simlify:

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



回答2:


Convert to datetime first using pd.to_datetime. You can then use datestrings in your loc statement:

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


来源:https://stackoverflow.com/questions/50774055/how-to-slice-a-pandas-time-series-using-a-logical-expression-involving-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!