lifetea
lifetea

Reputation: 27

How to do boolean indexing but assign both subsets to a variable at once?

Suppose that we have a dataframe with one column: Number.

By doing:

df_that_meets_condition = df[df.Number > 5]

we are going to have a df called df_that_meets_condition that has all the rows that meet the condition.

How can we assign the subset that does not meet the condition to another variable (suppose df_that_does_not_meet_condition) in one line?

An obvious way would be to just another line below with the reversed condition, but I'd like to have one line.

Upvotes: 0

Views: 29

Answers (2)

Arvind Kumar
Arvind Kumar

Reputation: 451

A simple one-liner would be:

df_that_meets_condition, df_that_does_not_meet_condition = df[df.number>5], df[~(df.number>5)]

Upvotes: 0

jezrael
jezrael

Reputation: 863166

It is a bit trick, but possible:

df_that_meets_condition, df_that_does_not_meet_condition = df[df.Number > 5], df[df.Number <= 5]

Or better is reuse existing mask:

m = df.Number > 5
df_that_meets_condition, df_that_does_not_meet_condition = df[m], df[~m]

Upvotes: 1

Related Questions