Skip to content Skip to sidebar Skip to footer

Get Previous Value Of Pandas Datetime Index

I have a pandas dataframe with datetime index Date 2013-02-22 00:00:00+00:00 0.280001 2013-02-25 00:00:00+00:00 0.109999 2013-02-26 00:00:00+00:00 -0.150000 2013-02-27 00:

Solution 1:

Here's one way to do it, first grab the integer location of the index key via get_loc:

In [15]: t = pd.Timestamp("2013-02-27 00:00:00+00:00")

In [16]: df1.index.get_loc(t)
Out[16]: 3

And then you can use iloc (to get the integer location, or slice by integer location):

In [17]:loc=df1.index.get_loc(t)In [18]:df.iloc[loc-1]Out[18]:Date2013-02-26 00:00:00-0.15Name:2,Dtype:objectIn [19]:df1.iloc[slice(max(0,loc-3),min(loc,len(df)))]# the min and max feel slightly hacky (!) but needed incase it's within top or bottom 3Out[19]:Date2013-02-22  0.2800012013-02-25  0.1099992013-02-26 -0.150000

See the indexing section of the docs.


I'm not quite sure how you set up your DataFrame, but that doesn't look like a Datetime Index to me. Here's how I got the DataFrame (with Timestamp index):

In [11]:df=pd.read_clipboard(sep='\s\s+',header=None,parse_dates=[0],names=['Date',None])In [12]:dfOut[12]:Date02013-02-22 00:00:00  0.28000112013-02-25 00:00:00  0.10999922013-02-26 00:00:00 -0.15000032013-02-27 00:00:00  0.13000142013-02-28 00:00:00  0.139999In [13]:df1=df.set_index('Date')In [14]:df1Out[14]:Date2013-02-22  0.2800012013-02-25  0.1099992013-02-26 -0.1500002013-02-27  0.1300012013-02-28  0.139999

Solution 2:

Could you just do df.shift().loc[date]?

Solution 3:

use shift to get the previous row values

data=[('2013-02-22 00:00:00+00:00',    0.280001)
,('2013-02-25 00:00:00+00:00',    0.109999)
,('2013-02-26 00:00:00+00:00',   -0.150000)
,('2013-02-27 00:00:00+00:00',    0.130001)
,('2013-02-28 00:00:00+00:00',    0.139999)]
df=pd.DataFrame(data=data,columns=['date','value'])
df['date']=pd.to_datetime(df['date'])

df['p_value']=df.value.shift(1)
df['pp_value']=df.value.shift(2)
df['ppp_value']=df.value.shift(3)
print(df)

output

         date                    value   p_value  pp_value  ppp_value
 02013-02-2200:00:00+00:000.280001NaNNaNNaN12013-02-2500:00:00+00:000.1099990.280001NaNNaN22013-02-2600:00:00+00:00-0.1500000.1099990.280001NaN32013-02-2700:00:00+00:000.130001-0.1500000.1099990.28000142013-02-2800:00:00+00:000.1399990.130001-0.1500000.109999

Post a Comment for "Get Previous Value Of Pandas Datetime Index"