Pandas Select DataFrame columns using boolean

What is returned is a Series with the column names as the index and the boolean values as the row values.

I think actually you want:

this should now work:

comb[criteria.index[criteria]]

Basically this uses the index values from criteria and the boolean values to mask them, this will return an array of column names, we can use this to select the columns of interest from the orig df.


In pandas 0.25:

comb.loc[:, criteria]

Returns a DataFrame with columns selected by the Boolean list or Series.

For multiple criteria:

comb.loc[:, criteria1 & criteria2]

And for selecting rows with an index criteria:

comb[criteria]

Note: The bit-wise operator & is required (not and). See Logical operators for boolean indexing in Pandas.

Other Note: If the criteria is an expression (e.g., comb.columnX > 3), and multiple criteria are used, remember to enclose each expression in parentheses! This is because &, | have higher precedence than >, ==, ect. (whereas and, or are lower precedence).

Tags:

Python

Pandas