Pandas日期时间索引的算术运算

2024-03-28 13:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

在pandas中,您可以通过基于传统整数位置/行的索引或基于日期时间的索引来访问时间序列的特定位置。基于整数的索引可以使用基本的算术运算来操作,例如,如果我有一个频率为12小时的时间序列的integer_index,并且我想在这之前一天访问该条目,那么我可以简单地执行integer_index - 2。然而,现实世界中的数据并不总是完美的,有时会丢失行。在这种情况下,此方法失败,因此能够使用基于日期时间的索引并从该索引中减去one day将是有帮助的。我该怎么做?

示例脚本:

# generate a sample time series
import pandas as pd
s = pd.Series(["A", "B", "C", "D", "E"], index=pd.date_range("2000-01-01", periods=5, freq="12h"))
print s

2000-01-01 00:00:00    A
2000-01-01 12:00:00    B
2000-01-02 00:00:00    C
2000-01-02 12:00:00    D
2000-01-03 00:00:00    E
Freq: 12H, dtype: object

# these to indices should access the same value ("C")
integer_index = 2
date_index = "2000-01-02 00:00"

print s[integer_index]  # prints "C"
print s[date_index]  # prints "C"

# I can access the value one day earlier by subtracting 2 from the integer index
print s[integer_index - 2]  # prints A

# how can I subtract one day from the date index?
print s[date_index - 1]  # raises an error 

这个问题的背景可以在我先前提交的一份报告中找到:

Fill data gaps with average of data from adjacent days

在那里,用户JohnE找到了解决我的问题的方法,使用基于整数位置的索引。他通过对时间序列重新采样来确保我得到等间距的数据。


Tags: the数据frompandasdateindex时间序列