zsljulius
zsljulius

Reputation: 4113

pandas timeseries select all records <= datetime

I am trying to select a subset of a timeseries where the dateindex should be smaller than a given date.

rng = pd.date_range(datetime.date(2013,1,1), datetime.date(2014,1,1), freq='M')
ts = pd.TimeSeries(range(len(rng)),index=rng)
ts[ts < datetime.date(2013,8,1)]

This throws the exception TypeError: can't compare datetime.date to int. Any idea how to get around this?

Upvotes: 0

Views: 139

Answers (1)

TomAugspurger
TomAugspurger

Reputation: 28956

Your last line compares the values in ts to a datetime.date. That's why your getting the TypeError with the unorderable types.

In [31]: ts[ts.index < np.datetime64('2013-08-01')]
Out[31]: 
2013-01-31    0
2013-02-28    1
2013-03-31    2
2013-04-30    3
2013-05-31    4
2013-06-30    5
2013-07-31    6
Freq: M, dtype: int64

Or even easier, with the special syntax for slicing time series:

In [33]: ts[:'2013-08-01']
Out[33]: 
2013-01-31    0
2013-02-28    1
2013-03-31    2
2013-04-30    3
2013-05-31    4
2013-06-30    5
2013-07-31    6
Freq: M, dtype: int64

Upvotes: 1

Related Questions