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
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
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP