filter rows in df and return if between string values - pandas

jonboy :

The following returns a boolean on which integers are an increase on the previous row.

However, I'm hoping to incorporate filtering rows based off strings. Specifically, I want to return rows between B and C. So whenever C follows B

import pandas as pd

df = pd.DataFrame({                   
    'X' : ['A','B','C','D'],
    'Y' : [1.0,1.0,2.0,1.0],              
   })

df = df.assign(Z = df.Y.diff().gt(0))

Out:

     X      Y
0  1.0  False
1  1.0  False
2  2.0   True
3  1.0  False

But I want to do use string values to return rows when C follows B.

Intended Out:

   X    Y
1  B  3.0
2  C  2.0
Quang Hoang :

Is it what you want:

# current is B and next is C
s = df['X'].eq('B') & df['X'].shift(-1).eq('C')

# current row and the next row
df[s | s.shift()]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319978&siteId=1