Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy the current row and the next row value in a new dataframe using python?

The df looks like below:

A   B   C
1   8   23
2   8   22
3   8   45
4   9   45
5   6   12
6   8   10
7   11  12
8   9   67

I want to create a new df with the occurence of 8 in 'B' and the next row value of 8.

New df: The df looks like below:

A   B   C
1   8   23
2   8   22
3   8   45
4   9   45
6   8   10
7   11  12
like image 568
hakuna_code Avatar asked Sep 24 '19 09:09

hakuna_code


1 Answers

Use boolean indexing with compared by shifted values with | for bitwise OR:

df = df[df.B.shift().eq(8) | df.B.eq(8)]
print (df)

   A   B   C
0  1   8  23
1  2   8  22
2  3   8  45
3  4   9  45
5  6   8  10
6  7  11  12
like image 104
jezrael Avatar answered Oct 18 '22 20:10

jezrael