Skip to content Skip to sidebar Skip to footer

How To Slice A Pandas Time Series Using A Logical Expression Involving Dates

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 involvi

Solution 1:

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

Solution 2:

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)Price2018-01-02  30.2400002018-01-03  30.6299992018-01-09  31.3099992018-01-10  31.4000002018-01-11  31.5800002018-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')))]

Post a Comment for "How To Slice A Pandas Time Series Using A Logical Expression Involving Dates"