Python Pandas Timeseries如何查找值高于特定值的最大序列

时间:2014-06-26 14:01:04

标签: python pandas

如何找到时间序列中最大的序列。 例如,我有DataFrame这样:

index      Value 
1-1-2012   10
1-2-2012   14
1-3-2012   15
1-4-2012   8
1-5-2012   7
1-6-2012   16
1-7-2012   17
1-8-2012   18

现在我想获得最长的序列: 这是从1-6-20121-8-2012的序列,包含3个条目。

由于 安雅

1 个答案:

答案 0 :(得分:2)

这有点笨拙,但做的工作。由于您未指定标题中提到的“特定值”,因此我选择12。

import pandas as pd

time_indecies = pd.date_range(start='2012-01-01', end='2012-08-01', freq='MS')
data = [10, 14, 15, 8, 7, 16, 17, 18]
df = pd.DataFrame({'vals': data, 't_indices': time_indecies })

threshold = 12
df['tag'] = df.vals > threshold

# make another DF to hold info about each region
regs_above_thresh = pd.DataFrame()

# first row of consecutive region is a True preceded by a False in tags
regs_above_thresh['start_idx']  = \
    df.index[df['tag'] & ~ df['tag'].shift(1).fillna(False)]

# last row of consecutive region is a False preceded by a True   
regs_above_thresh['end_idx']  = \
   df.index[df['tag'] & ~ df['tag'].shift(-1).fillna(False)] 

# how long is each region
regs_above_thresh['spans'] = \
    [(spam[0] - spam[1] + 1) for spam in \
    zip(regs_above_thresh['end_idx'], regs_above_thresh['start_idx'])]

# index of the region with the longest span      
max_idx = regs_above_thresh['spans'].argmax()

# we can get the start and end points of longest region from the original dataframe 
df.ix[regs_above_thresh.ix[max_idx][['start_idx', 'end_idx']].values]

连续的区域聪明来自behzad.nouri的solution here