Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Biggest index smaller then a date

Given the following exemplary Pandas DataFrame x:

             a    b
2014-08-07   0.1  2.0
2014-08-18   0.2  4.0
2014-12-16   0.3  0.0
2015-01-16   0.4  2.3
2015-02-16   0.5  2.1
2015-03-18   0.6  7.0

The indices are of the type datetime.date.

I want to write a function that takes a parameter start of the type datetime.datetime such that it gives me the biggest index which is smaller then start.

For example, for start = datetime.datetime(2015, 1, 20, 17, 30) the biggest index that is smaller then start is, is 2015-01-16.

This would give me the most recent change in a and b namely x.loc[dt(2015,1,16)].

like image 860
Joachim Avatar asked Oct 16 '25 16:10

Joachim


1 Answers

The pandas asof function is meant for this:

x.index.asof(start)

It can be used on series or on datetime indexes.

See:

http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DatetimeIndex.asof.html

like image 110
Pablojim Avatar answered Oct 18 '25 07:10

Pablojim