Reputation: 31206
So I have a pandas dataframe indexed by date.
I need to grab a value from the dataframe by date...and then grab the value from the dataframe that was the day before...except I can't just subtract a day, since weekends and holidays are missing from the data.
It would be great if I could write:
x = dataframe.ix[date]
and
i = dataframe.ix[date].index
date2 = dataframe[i-1]
I'm not married to this solution. If there is a way to get the date or index number exactly one prior to the date I know, I would be happy...(short of looping through the whole dataframe and testing to see if I have a match, and saving the count...)
Upvotes: 2
Views: 806
Reputation: 394041
Use .get_loc
to get the integer position of a label value in the index:
In [51]:
df = pd.DataFrame(index=pd.date_range(start=dt.datetime(2015,1,1), end=dt.datetime(2015,2,1)), data={'a':np.arange(32)})
df
Out[51]:
a
2015-01-01 0
2015-01-02 1
2015-01-03 2
2015-01-04 3
2015-01-05 4
2015-01-06 5
2015-01-07 6
2015-01-08 7
2015-01-09 8
2015-01-10 9
2015-01-11 10
2015-01-12 11
2015-01-13 12
2015-01-14 13
2015-01-15 14
2015-01-16 15
2015-01-17 16
2015-01-18 17
2015-01-19 18
2015-01-20 19
2015-01-21 20
2015-01-22 21
2015-01-23 22
2015-01-24 23
2015-01-25 24
2015-01-26 25
2015-01-27 26
2015-01-28 27
2015-01-29 28
2015-01-30 29
2015-01-31 30
2015-02-01 31
Here using .get_loc
on the index will return the ordinal position:
In [52]:
df.index.get_loc('2015-01-10')
Out[52]:
9
pass this value using .iloc
to get a row value by ordinal position:
In [53]:
df.iloc[df.index.get_loc('2015-01-10')]
Out[53]:
a 9
Name: 2015-01-10 00:00:00, dtype: int32
You can then subtract 1
from this to get the previous row:
In [54]:
df.iloc[df.index.get_loc('2015-01-10') - 1]
Out[54]:
a 8
Name: 2015-01-09 00:00:00, dtype: int32
Upvotes: 2