Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return dataframe subset based on a list of boolean values

I'm trying to slice a dataframe based on list of values, how would I go about this?

Say I have an expression or a list l = [0,1,0,0,1,1,0,0,0,1]

How to return those rows in a dataframe, df, when the corresponding value in the expression/list is 1? In this example, I would include rows where index is 1, 4, 5, and 9.

like image 361
user7180132 Avatar asked Aug 03 '17 21:08

user7180132


People also ask

Can you have a list of booleans?

22.1-1 IsBlist. A boolean list ("blist") is a list that has no holes and contains only true and false . Boolean lists can be represented in an efficient compact form, see 22.5 for details. Boolean lists are lists and all operations for lists are therefore applicable to boolean lists.

Is boolean indexing possible in DataFrame?

Boolean indexing helps us to select the data from the DataFrames using a boolean vector. We need a DataFrame with a boolean index to use the boolean indexing.


1 Answers

You can use masking here:

df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]

So we construct a boolean array with true and false. Every place where the array is True is a row we select.

Mind that we do not filter inplace. In order to retrieve the result, you have to assign the result to an (optionally different) variable:

df2 = df[np.array([0,1,0,0,1,1,0,0,0,1],dtype=bool)]
like image 94
Willem Van Onsem Avatar answered Oct 30 '22 09:10

Willem Van Onsem