Search code examples
pythonpython-3.xdataframeiterationrows

Get the rows of dataframe based on the consecutive values of one column


Are there way to get consecutive rows according to value of specific column? For example:

column1 column2 View
row1 1 2 c
row2 3 4 a
row3 5 6 p
row4 7 8 p
row5 9 10 n

I need to get the rows that have the letter of word 'app' as View, so in this example I need to save row2, row3 and row4 in a list.


Solution

  • Not the pythonic way, but doing the work:

    keep = []
    for i in range(len(df) - 2):
        if (df.View[i]=='a') & (df.View[i+1] =='p') & (df.View[i+2] =='p'):
            keep.append(df[i])
            keep.append(df[i+1])
            keep.append(df[i+2])
    

    Result:

    enter image description here