AnswerBun.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!

Related Questions

How to Deserialize a list of objects from json in flutter

8  Asked on January 28, 2021 by gainz

     

How to pass input variable in structure directive?

1  Asked on January 27, 2021 by alice-messis

 

How to iterate over a list of floats in python

4  Asked on January 27, 2021 by joeyhoward988

 

Can I run docker system prune -a without downtime

1  Asked on January 27, 2021 by aswin-george

 

Calculating total Price of groceries with execptions in Python

4  Asked on January 27, 2021 by shemtheultimate

 

handling multiple useState inside conditional ternary

2  Asked on January 27, 2021 by kachi-cheong

     

react-native existing app crash on Android 4.1

0  Asked on January 27, 2021 by s-leg3ndz

     

HTML table widths set proportionally

1  Asked on January 27, 2021 by mayur-arora

   

Alsa issues on Raspberry pi

1  Asked on January 27, 2021 by suraj-hebbar-shankar

 

How to merge dictionaries with the same key and value in Python

1  Asked on January 26, 2021 by arbin-bulaybulay

 

AJAX switching HTML

1  Asked on January 26, 2021 by mimi

       

Using request to return a json value

1  Asked on January 26, 2021 by gta-sprx

 

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir