在pandas dataframe列中查找特定模式

时间:2017-07-07 09:52:08

标签: python pandas

我想在pandas dataframe列中找到一个特定的模式,并返回相应的索引值,以便对数据帧进行子集化。

这是一个带有可能模式的示例数据框:

要生成数据帧的代码段

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(2017, 7, 7).strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

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

数据框:

            ColA  ColB
Dates                 
2017-07-07   103    92
2017-07-08    92    96
2017-07-09   107   109
2017-07-10   100    91
2017-07-11    90   107
2017-07-12   105    99
2017-07-13    90   104
2017-07-14    90   105
2017-07-15   109   104
2017-07-16    94    90

此处,感兴趣的模式发生在日期Column A2017-07-10的{​​{1}}中,这就是我想要最终得到的结果:

期望的输出:

2017-07-12

如果多次出现相同的模式,我想以相同的方式对数据帧进行子集化,并计算模式出现的次数,但我希望只要我完成第一步就可以更直接。

感谢您的任何建议!

4 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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

答案 2 :(得分:1)

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

为了找到这些索引,单行就足够了:

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

然后按照另一个答案说来获取你想要的子集。

答案 3 :(得分: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)