2017-07-07 147 views
4

我想在熊猫数据框列中查找特定模式,并返回相应的索引值以便为数据框设置子集。在熊猫数据框中查找特定模式

下面是一个可能的图案的样本数据帧:

import pandas as pd 
import numpy as np 

Observations = 10 
Columns = 2 
np.random.seed(123) 
df = pd.DataFrame(np.random.randint(90,110,size=(Observations, Columns)), 
       columns = ['ColA','ColB']) 
datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'), 
        periods=Observations).tolist() 
df['Dates'] = datelist 
df = df.set_index(['Dates']) 

pattern = [100,90,105] 
print(df) 

enter image description here

在此,图案在列A的日期2017年7月10日到2017年7月12日发生,并且这就是我想和落得什么:

enter image description here

如果出现同样的模式几次,我想子集d ata框架的方式相同,并且也计算该模式出现的次数,但是我希望只要我把第一步整理出来就更简单了。

谢谢你的任何建议!

回答

2

这里是一个解决方案:

检查模式是使用rolling任何列中找到。 这会给你组的最后一个索引匹配模式

matched = df.rolling(len(pattern)).apply(lambda x: all(np.equal(x, pattern))) 
matched = matched.sum(axis = 1).astype(bool) #Sum to perform boolean OR 

matched 
Out[129]: 
Dates 
2017-07-07 False 
2017-07-08 False 
2017-07-09 False 
2017-07-10 False 
2017-07-11 False 
2017-07-12  True 
2017-07-13 False 
2017-07-14 False 
2017-07-15 False 
2017-07-16 False 
dtype: bool 

对于每场比赛,加上完整图案的指标:

idx_matched = np.where(matched)[0] 
subset = [range(match-len(pattern)+1, match+1) for match in idx_matched] 

获取的所有模式:

result = pd.concat([df.iloc[subs,:] for subs in subset], axis = 0) 

result 
Out[128]: 
      ColA ColB 
Dates     
2017-07-10 100 91 
2017-07-11 90 107 
2017-07-12 105 99 
1

最短的方法是找到模式开始的索引。然后你只需要选择以下三行。

为了找到这些指标,一个班轮是不够的:

indexes=df[(df.ColA==pattern[0])&(df["ColA"].shift(-1)==pattern[1])&(df["ColA"].shift(-2)==pattern[2])].index 

然后做作为对方的回答说,以获得您想要的子集。

1
for col in df: 
    index = df[col][(df[col] == pattern[0]) & (df[col].shift(-1) == pattern[1]) & (df[col].shift(-2) == pattern[2])].index 
    if not index.empty: print(index) 
3

使用列表内涵的法宝:

[df.index[i - len(pattern)] # Get the datetime index 
for i in range(len(pattern), len(df)) # For each 3 consequent elements 
if all(df['ColA'][i-len(pattern):i] == pattern)] # If the pattern matched 

# [Timestamp('2017-07-10 00:00:00')] 
+0

这是迄今为止最优雅的解决方案。 – baloo