Eka
Eka

Reputation: 15002

How to select rows from a certain date in pandas dataframe with datetime index

I have a dataframe with datetime as index. similar to the below one

>>> data.index
Index(['2019-05-15 23:45:00', '2019-05-15 23:46:00', '2019-05-15 23:47:00',
       '2019-05-15 23:48:00', '2019-05-15 23:49:00', '2019-05-15 23:50:00',
       '2019-05-15 23:52:00', '2019-05-15 23:53:00', '2019-05-15 23:54:00',
       '2019-05-15 23:55:00',
       ...
       '2019-05-19 05:36:00', '2019-05-19 05:37:00', '2019-05-19 05:38:00',
       '2019-05-19 05:39:00', '2019-05-19 05:40:00', '2019-05-19 05:41:00',
       '2019-05-19 05:42:00', '2019-05-19 05:43:00', '2019-05-19 05:44:00',
       '2019-05-19 05:45:14'],
      dtype='object', name='date', length=989)

I need to select all the rows which corresponding to the date 2019-05-16. I tried these two methods.

1) data['2019-05-16'] gives KeyError: '2019-05-16'

2) data.loc['2019-05-16'] gives KeyError: 'the label [2019-05-16] is not in the [index]'

Upvotes: 1

Views: 117

Answers (1)

jezrael
jezrael

Reputation: 863741

Convert values to DatetimeIndex first, because now it is string repr of datetimes:

data.index = pd.to_datetime(data.index)

data = pd.DataFrame({'a':range(3)}, 
                     index=['2019-05-15 23:45:00','2019-05-16 23:46:00','2019-05-17 23:47:00'])

data.index = pd.to_datetime(data.index)
print(data)
                     a
2019-05-15 23:45:00  0
2019-05-16 23:46:00  1
2019-05-17 23:47:00  2

Your solution working, if exist at least one index value with date:

print (data['2019-05-16'])
                     a
2019-05-16 23:46:00  1

If not exist, there are alternatives:

print (data[data.index.normalize() == '2019-05-18'])
Empty DataFrame
Columns: [a]
Index: []

print (data[data.index.floor('d') == '2019-05-18'])
Empty DataFrame
Columns: [a]
Index: []

print (data[data.index.date == '2019-05-18'])
Empty DataFrame
Columns: [a]
Index: []

Upvotes: 1

Related Questions