Reputation: 4827
Selecting a single date from a timeserie gives a KeyError.
Setup:
import pandas as pd
import numpy as np
ts = pd.DataFrame({'date': pd.date_range(start = '1/1/2017', periods = 5),
'observations': np.random.choice(range(0, 100), 5, replace = True)}).set_index('date')
Dataframe:
observations
date
2017-01-01 58
2017-01-02 88
2017-01-03 53
2017-01-04 4
2017-01-05 26
How do I select the number of observations for a single date?
ts['2017-01-01']
Returns: KeyError: '2017-01-01'
But...
ts['2017-01-01':'2017-01-01']
...seems to work just fine.
Any suggestions how to select/subset with a single date?
Upvotes: 1
Views: 91
Reputation: 29635
As @scnerd pointed out, when you do ts['2017-01-01']
it tries to find '2017-01-01' as a column's name of the dataframe ts
, which gives you an KeyError
as none of the columns in ts
has this name
In order to look for an index' name, as in your example 'date' is set as index, you need to use loc
method such as ts.loc['2017-01-01']
and you will get:
observations 54
Name: 2017-01-01 00:00:00, dtype: int32
Upvotes: 2