在 pandas 中,您可以通过基于经典整数位置/行的索引或基于日期时间的索引来访问时间序列的特定位置。可以使用基本算术运算来操作基于整数的索引,例如如果我有一个integer_index
对于频率为 12 小时的时间序列,并且我想恰好在此之前的一天访问该条目,我可以简单地执行以下操作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
这个问题的背景可以在我之前提交的文章中找到:
用相邻日期的数据平均值填补数据空白 https://stackoverflow.com/questions/25909115/fill-data-gaps-with-average-of-data-from-adjacent-days
用户 JohnE 找到了解决我的问题的方法,该方法使用基于整数位置的索引。他通过对时间序列重新采样来确保我拥有等间距的数据。
您的日期时间索引不是基于字符串,而是基于DatetimeIndex http://pandas.pydata.org/pandas-docs/stable/timeseries.html#datetimeindex意味着你可以使用datetime https://docs.python.org/3.4/library/datetime.html#datetime-objects适当索引的对象,而不是字符串looks就像约会一样。
下面的代码转换date_index
into a datetime
对象,然后使用timedelta(days=1) https://docs.python.org/3.4/library/datetime.html#timedelta-objects从中减去“一天”。
# generate a sample time series
import pandas as pd
from datetime import datetime, timedelta
s = pd.Series(["A", "B", "C", "D", "E"], index=pd.date_range("2000-01-01", periods=5, freq="12h"))
print(s)
# these two indices should access the same value ("C")
integer_index = 2
# Converts the string into a datetime object
date_index = datetime.strptime("2000-01-02 00:00", "%Y-%m-%d %H:%M")
print(date_index) # 2000-01-02 00:00:00
print(s[integer_index]) # prints "C"
print(s[date_index]) # prints "C"
print(s[integer_index - 2]) # prints "A"
one_day = timedelta(days=1)
print(s[date_index - one_day]) # prints "A"
print(date_index - one_day) # 2000-01-01 00:00:00
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)