I want to use a boolean to select the columns with more than 4000 entries from a dataframe comb
which has over 1,000 columns. This expression gives me a Boolean
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).
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.
You can also use:
# To filter columns (assuming criteria length is equal to the number of columns of comb)comb.ix[:, criteria]comb.iloc[:, criteria.values] # To filter rows (assuming criteria length is equal to the number of rows of comb) comb[criteria]
I'm using this, it's cleaner
comb.values[:,criteria]
credit: https://stackoverflow.com/a/43291257/815677
Another solution is to transpose comb
to make its columns act as its index, then transpose on the resulting subset:
comb.T[criteria].T
Again, not particularly elegant, but at least shorter/less repetitive than the leading solution.