Pandas - select a pair of consecutive lines that match the criteria

I have a dataframe that looks like this:

>>> a_df
    state
1    A
2    B
3    A
4    B
5    C

What I would like to do is return all consecutive lines corresponding to a specific sequence. For example, if this is a sequence ['A', 'B'], then rows whose state Afollowed immediately Bmust be returned. In the above example:

>>> cons_criteria(a_df, ['A', 'B'])
    state
1    A
2    B
3    A
4    B

Or, if the selected array ['A', 'B', 'C'], then the output should be

>>> cons_criteria(a_df, ['A', 'B', 'C'])
    state
3    A
4    B
5    C

I decided to do this while maintaining the current state as well as the following state:

>>> df2 = a_df.copy()
>>> df2['state_0'] = a_df['state']
>>> df2['state_1'] = a_df['state'].shift(-1)

Now I can match with state_0and state_1. But this only returns the very first record:

>>> df2[(df2['state_0'] == 'A') & (df2['state_1'] == 'B')]
    state
1    A
3    A

, ? pandas?

+4
2

​​

def match_slc(s, seq):
    # get list, makes zip faster
    l = s.values.tolist()
    # count how many in sequence
    k = len(seq)
    # generate numpy array of rolling values
    a = np.array(list(zip(*[l[i:] for i in range(k)])))
    # slice an array from 0 to length of a - 1 with 
    # the truth values of wether all 3 in a sequence match
    p = np.arange(len(a))[(a == seq).all(1)]
    # p tracks the beginning of a match, get all subsequent
    # indices of the match as well.
    slc = np.unique(np.hstack([p + i for i in range(k)]))
    return s.iloc[slc]

s = pd.Series(list('ABABC'))

print(match_slc(s, list('ABC')), '\n')
print(match_slc(s, list('AB')), '\n')

2    A
3    B
4    C
dtype: object 

0    A
1    B
2    A
3    B
dtype: object 
+3

, , . dataframe , 2 ABC:

a_df=pd.DataFrame(['A','B','A','B','C','D','A','A','B','C','E'],
                  columns=["state"])

:

pattern = ['A','B','C']

:

starts = set(a_df[a_df['state']          =='A'].index) & 
         set(a_df[a_df['state'].shift(-1)=='B'].index) & 
         set(a_df[a_df['state'].shift(-2)=='C'].index)
print(starts)
# {2, 7}

:

starts = set.intersection(
           *[set(a_df[a_df['state'].shift(-i)==value].index) 
             for i,value in enumerate(pattern)])

3- :

result = [a_df.ix[range(i, i+3)] for i in starts]
print(result)
# [  state
# 2     A
# 3     B
# 4     C,   state
# 7     A
# 8     B
# 9     C]

:

result = [a_df.ix[range(i, i+len(pattern))] for i in starts]
+2

Source: https://habr.com/ru/post/1663701/


All Articles