python - 获取 Pandas 日期时间索引的先前值

标签 python pandas

我有一个带有日期时间索引的 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

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

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

我搜索过这个但是因为我的索引是一个日期所以我不能搜索

df.ix[int-1]

最佳答案

这里有一种方法,首先通过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

然后您可以使用 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

参见 indexing section of the docs .


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

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

关于python - 获取 Pandas 日期时间索引的先前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15162605/

相关文章:

python - 有没有办法在 pandas DataFrame 中将 'search' 用于列中的 2 个特定数字并返回索引(如果存在)?

python - to_sql pyodbc count 字段不正确或语法错误

python - 使用 Python 在 Plotly 中分组图例

python - wxpython 的 Intellisense 之类的小部件是什么

Python:帮助优化代码

pandas - 在 IPython 中绘图时抑制对象的输出

python - 克服字符串不可变性的 "disadvantages"

python - 在 pandas 方法链接期间访问以前的数据帧

python - 从文件中检索与文件中指定的给定区域相对应的数字

python - 按名称将行移动到 df 中的所需位置