How to select the actual row and the above based on specific string in pandas?

Viewed 48

this is an example of a bigger dataframe:

    column1
0   a
1   b
2   x
3   c
4   b
5   x
6   d
7   x
8   e
9   e

In this dataframe, I would like to select every row that has 'x' on it and also the exaclty rows above each of these ones. And then I want to create another dataframe with these new rows.

The final dataframe should be like this:

        column1
    1   b
    2   x
    4   b
    5   x
    6   d
    7   x

Anyone could help me?

Thanks

2 Answers

You can use shift:

print (df.loc[df["column1"].eq("x")|df["column1"].eq("x").shift(-1)])

  column1
1       b
2       x
4       b
5       x
6       d
7       x

use shift()

df = pd.DataFrame({'column1':['a','b','x','c','b','x','d','x','e','e']})
df[(df['column1'] == 'x') | (df['column1'].shift(-1) == 'x')]

produces


column1
1   b
2   x
4   b
5   x
6   d
7   x
Related