简体   繁体   English

PANDAS:使用日期时间索引将熊猫系列 n 行切成过去

[英]PANDAS: Slice pandas series n rows into the past with a datetime index

upper_lower_bound returns 2 datetime indices from my dataframe. upper_lower_bound从我的数据upper_lower_bound返回 2 个日期时间索引。 I only use one at a time and they have no relation to each other.我一次只使用一个,它们之间没有关系。

I want to get the max() value of the previous 6 rows data from a dataframe highP but I get an error if I try to subtract 6 from it.我想从数据帧highP获取前 6 行数据的max()值,但是如果我尝试从中减去 6,则会出现错误。 dt.timedelta(6) subtracts 6 days from the df but there are missing days in the df so it doesn't provide the correct answer. dt.timedelta(6)从 df 中减去 6 天,但 df 中缺少天数,因此它没有提供正确的答案。

How can I slice highP so that it gives me the previous six values in that series for eg.我如何切片highP以便它为我提供该系列中的前六个值,例如。

highP.loc[i - 6: i].max() given that i is a datetime index? highP.loc[i - 6: i].max()假设i是日期时间索引?

any help would be greatly appreciated!任何帮助将不胜感激!

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

How about sorting by time and taking last elements with tail?如何按时间排序并使用尾部获取最后一个元素? For generality, I will use notations with:一般而言,我将使用以下符号:

  • dataframe = df数据框 = df
  • time column = t时间列 = t
  • value column = val值列 = val
  • certain location = i某个位置 = i

first we obtain a df of sample with time < time at i :首先,我们在i处获得时间 < 时间的 df 样本:

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

then we sort by time:然后我们按时间排序:

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

then we take last five with 'tail':然后我们用'tail'取最后五个:

five_before = before_df.tail(5)

then we max over value:然后我们最大化价值:

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

Does this solve your question?这能解决你的问题吗?

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM