Juvago
Juvago

Reputation: 55

Python Dataframe: select rows based on previous rows values

I have the following Python dataframe object df:

   1_count  136088194_count  136088202_count  Label
1  0.0      0.0              0.0              False
2  0.0      0.0              0.0              False
3  0.0      0.0              0.0              True 
4  0.0      0.0              0.0              False
5  0.0      0.0              0.0              False
6  0.0      0.0              0.0              True 
7  6.0      0.0              0.0              False
8  0.0      0.0              0.0              False
9  0.0      0.0              0.0              False

I want to create a new Dataframe, which contains all the rows which appear before the "Label" value "True" in last column.

In this example case it would be the rows 2 and 5.

The result should look like this:

   1_count  136088194_count  136088202_count  Label
2  0.0      0.0              0.0              False
5  0.0      0.0              0.0              False

I know that I can access the rows 3 and 6 via:

df = df.loc[df['Label']==True]

but how do I shift the Dataframe to the previous rows?

Upvotes: 0

Views: 276

Answers (1)

Abhi
Abhi

Reputation: 4233

One way would be to use shift

df = df.loc[df.Label.shift(-1)==True]
print(df)

# Output

   1_count  136088194_count 136088202_count   Label
2   0.0          0.0             0.0          False
5   0.0          0.0             0.0          False

Upvotes: 1

Related Questions