pandas 获取熊猫日期时间索引的先前值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15162605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:41:02  来源:igfitidea点击:

get previous value of pandas datetime index

pythonpandas

提问by trbck

I have a pandas dataframe with datetime index

我有一个带有日期时间索引的Pandas数据框

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:00:00+00:00    0.130001
2013-02-28 00:00:00+00:00    0.139999
Name: MOM12

and want to evaluate the previous three values of the given datetime index.

并且想要评估给定日期时间索引的前三个值。

date = "2013-02-27 00:00:00+00:00"
df.ix[date]

I searched for this but since my index is a date I can't do

我搜索了这个,但因为我的索引是一个我不能做的日期

df.ix[int-1]

采纳答案by Andy Hayden

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

这是一种方法,首先通过以下方式获取索引键的整数位置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):

然后您可以使用iloc(获取整数位置,或按整数位置切片):

In [17]: loc = df1.index.get_loc(t)

In [18]: df.iloc[loc - 1]
Out[18]: 
Date    2013-02-26 00:00:00
                      -0.15
Name: 2, Dtype: object

In [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 3
Out[19]:                         
Date                    
2013-02-22  0.280001
2013-02-25  0.109999
2013-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):

我不太确定您是如何设置 DataFrame 的,但这对我来说看起来不像是日期时间索引。这是我获得 DataFrame 的方式(带有时间戳索引):

In [11]: df = pd.read_clipboard(sep='\s\s+', header=None, parse_dates=[0], names=['Date', None])

In [12]: df
Out[12]: 
                 Date          
0 2013-02-22 00:00:00  0.280001
1 2013-02-25 00:00:00  0.109999
2 2013-02-26 00:00:00 -0.150000
3 2013-02-27 00:00:00  0.130001
4 2013-02-28 00:00:00  0.139999

In [13]: df1 = df.set_index('Date')

In [14]: df1
Out[14]:                
Date                
2013-02-22  0.280001
2013-02-25  0.109999
2013-02-26 -0.150000
2013-02-27  0.130001
2013-02-28  0.139999

回答by dionysos137

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

你能做df.shift().loc[date]吗?