问题
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 date
s only and index
contains also time
s 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