【问题标题】:How to get last n-number of rows with datetime index in a pandas dataframe?如何在熊猫数据框中使用日期时间索引获取最后 n 行?
【发布时间】: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


【解决方案1】:

我认为您需要iloc 来选择职位:

pos = data2.index.get_loc(end_index)
c = data2.iloc[pos - 32: pos].bfill().ffill()

pos = data3.index.get_loc(end_index)
d = data3.iloc[pos - 32: pos].bfill().ffill()

pos = data2.index.get_loc(end_index)
e = data4.iloc[pos - 32: pos].bfill().ffill()

【讨论】:

  • 这个问题是 data2.index.get_loc(end_index) 找不到特定的索引 loc 因为它关闭了几个小时。这会引发一个关键错误。好主意!
【解决方案2】:

正如 Code Different 所建议的,使用 .tail(32) 和 loc 索引是可行的!

b = data1.loc[: test_index].bfill().ffill().tail(32)
c = data2.loc[: test_index].bfill().ffill().tail(32)
d = data3.loc[: test_index].bfill().ffill().tail(32)
e = data4.loc[: test_index].bfill().ffill().tail(32)

【讨论】:

    猜你喜欢
    • 2022-08-07
    • 2021-05-03
    • 2014-09-21
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2021-03-19
    • 2021-03-12
    • 2017-02-08
    相关资源
    最近更新 更多