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.
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With