1

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

0

1 Answer 1

1

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: []
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.