TransWikia.com

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

Stack Overflow Asked by user026 on November 29, 2020

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

Correct answer by Henry Yik on November 29, 2020

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

Answered by piterbarg on November 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP