简体   繁体   中英

How to filter a dataframe of dates and hours by a list of dates?

I have the following dataframe, with several days and a measure every 15minutes:

                 CONSUMPTION
2016-11-01 01:00:00  3539
2016-11-01 01:15:00  3560
2016-11-01 01:30:00  3505
....
2016-11-02 01:00:00  3400
2016-11-02 01:15:00  3447
....
2016-11-03 01:00:00  2400
2016-11-03 01:15:00  2447

Every works if ask for a simple day:

df['2016-11-01']

and I get all the measure for that day, 96 measures:

    CONSUMPTION
2016-11-01 01:00:00  3539
2016-11-01 01:15:00  3560
2016-11-01 01:30:00  3505
....

But my problem is that I want to get a list of dates, and this doesn't work:

df[['2016-11-01','2016-11-03']]

The most I have achieved is this (but this is not what I want, observed that 1 get a measure per day, instead my 96 expected measures):

qwe=['2016-11-01','2016-11-03']
df.ix[df.index.to_datetime().isin(qwe)]

            CONSUMPTION
2016-11-01  3539
2016-11-03  2400

Any idea would be appreciated.....

Floor the datetime to Day and then use isin and loc ie

li = ['2016-11-01','2016-11-02']
df.loc[(df.index.floor('D').isin(li)),:]

                    CONSUMPTION
Date                            
2016-11-01 01:00:00         3539
2016-11-01 01:15:00         3560
2016-11-01 01:30:00         3505
2016-11-02 01:00:00         3400
2016-11-02 01:15:00         3447

This works for hours :

hours = [0, 6, 12, 18]
df.loc[(df.index.hour.isin(hours)),:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM