【发布时间】:2019-12-02 03:12:22
【问题描述】:
我正在尝试从按日期索引的 pandas 数据框中获取最后 32 个数据点。我有多个重新采样的数据帧,编号为 data1、data2、data3 等...已从 1 小时、4 小时、12 小时、1 天重新采样。
我已经尝试将 get_loc 与我想为每个数据帧结束的日期时间索引一起使用,但问题是我的日期时间索引的采样方式不同,因此日期时间索引会关闭几个小时。我还尝试从 datetime 中减去等效小时数,但这并不能保证 32 个数据点
from datetime import timedelta
import pandas as pd
data1 = data.resample('4H').last().ffill()
data2 = data.resample('6H').last().ffill()
data3 = data.resample('12H').last().ffill()
data4 = data.resample('1D').last().ffill()
# datetime I want to end my row with and get last 32 values
end_index = pd.Timestamp("2019-02-27 00:00:00+00:00")
# this method does not always guarantee 32 data points
b = data1.loc[end_index - timedelta(hours=192): end_index].bfill().ffill()
c = data2.loc[end_index - timedelta(hours=380): end_index].bfill().ffill()
d = data3.loc[end_index - timedelta(hours=768): end_index].bfill().ffill()
e = data4.loc[end_index - timedelta(hours=768): end_index].bfill().ffill()
# this method throws an error because end_index is off by a few hours sometimes
pos = data1.index.get_loc(end_index)
b = data1.loc[pos - 32: pos].bfill().ffill()
pos = data2.index.get_loc(end_index)
c = data2.loc[pos - 32: pos].bfill().ffill()
pos = data3.index.get_loc(end_index)
d = data3.loc[pos - 32: pos].bfill().ffill()
pos = data2.index.get_loc(end_index)
e = data4.loc[pos - 32: pos].bfill().ffill()
密钥错误:1498208400000000000 在处理上述异常的过程中,又出现了一个异常:
【问题讨论】:
-
你试过
data1.tail(32)吗? -
谢谢,我忘记了 pandas 中的 tail(32)。 b = data1.loc[: test_index].bfill().ffill().tail(32) 并且有效!
-
您能否发布一个答案,以便我将其标记为获胜者!
标签: python pandas datetime indexing