【问题标题】:PANDAS: Slice pandas series n rows into the past with a datetime index熊猫:使用日期时间索引将熊猫系列 n 行切片到过去
【发布时间】:2026-01-16 06:05:01
【问题描述】:

upper_lower_bound 从我的数据框中返回 2 个日期时间索引。我一次只使用一个,它们之间没有任何关系。

我想从数据帧 highP 中获取前 6 行数据的 max() 值,但如果我尝试从中减去 6,则会出现错误。 dt.timedelta(6) 从 df 中减去 6 天,但 df 中缺少天数,因此无法提供正确答案。

我如何对highP 进行切片,以便它为我提供该系列中的前六个值。

highP.loc[i - 6: i].max() 假设 i 是日期时间索引?

任何帮助将不胜感激!

upper_lower_bound = df[(isoHL['IH'] >= 1) | (isoHL['IL'] >= 1)].index[-3:-1]

if isoHL.loc[upper_lower_bound[-1]]['IH'] == 1 and isoHL.loc[upper_lower_bound[-1]]['IL'] == 0:
    upper_bound = highP.loc[upper_lower_bound[-1] - dt.timedelta(6):upper_lower_bound[-1]].max()
else:
    pass

【问题讨论】:

    标签: python pandas numpy dataframe series


    【解决方案1】:

    按时间排序并用尾部取最后一个元素怎么样? 为概括起见,我将使用以下符号:

    • 数据框=df
    • 时间栏=t
    • 值列 = val
    • 某个位置 = i

    首先我们获得一个样本的df,时间i:

    before_df = df[df['t'] <= df.loc[i, 't']]

    然后我们按时间排序:

    before_df = before_df.sort_values(by=['t'])

    然后我们用'tail'取最后五个:

    five_before = before_df.tail(5)

    然后我们最大化价值:

    val = five_before['val'].max()

    这能解决你的问题吗?

    `

    【讨论】:

    • 非常感谢您的帮助,我将代码稍微调整为我所拥有的并且现在可以完美运行!非常感谢
    最近更新 更多