简体   繁体   中英

Pandas DF - Find a sequence in consecutive columns in a row

I have the following data frame and I want to find [c, d] in columns next to each other (exact sequence).

In the example below the rows 0 and 2 have [c, d] in columns next to each other.

  A B C D
0 a c d e
1 a d e c
2 b e c d
3 c a d e

I have tried df.eq('c') & df.eq('d') but this will find 'c' and 'd' in any order in a row.

Shift values by row for one of the comparisons, and then check if both conditions are true at the same location:

(df.shift(axis=1).eq('c') & df.eq('d')).any(1)

#0     True
#1    False
#2     True
#3    False
#dtype: bool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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