48

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 (True/False) result:

criteria = comb.ix[:,'c_0327':].count()>4000

I want to use it to select only the True columns to a new Dataframe.
The following just gives me "Unalignable boolean Series key provided":

comb.loc[criteria,]

I also tried:

comb.ix[:, comb.ix[:,'c_0327':].count()>4000] 

Similar to this question answer dataframe boolean selection along columns instead of row but that gives me the same error: "Unalignable boolean Series key provided"

comb.ix[:,'c_0327':].count()>4000

yields:

c_0327    False
c_0328    False
c_0329    False
c_0330    False
c_0331    False
c_0332    False
c_0333    False
c_0334    False
c_0335    False
c_0336    False
c_0337     True
c_0338    False
.....
2
  • don't you want comb[criteria.columns]? Commented Mar 26, 2015 at 15:19
  • 1
    comb[criteria.columns] gives me "'Series' object has no attribute 'columns'" Commented Mar 26, 2015 at 15:24

7 Answers 7

50

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am surprised to see, there is no shorter (more straightforward ) way of doing this.
There is, this answer is 5 years old and outdated. See my answer below for the straightforward way
@johnDanger Nice answer, but I'm not sure I'd agree that going from "m[f] for row filtering" to "m.loc[:,f] for column filtering" is straightforward.
The "straightforwardness" in @johnDanger's answer is that you only need criteria once, and hence you do not need to define the variable separately (but can just use the expression itself ion m.loc[:, expression_of_criteria_itself]).
38

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).

Comments

7

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]

2 Comments

The first answer looks the most elegant for masked column selection. The only trick is that one needs to do comb.iloc[:, criteria.values], as a series is not a valid argument into iloc slicing of this type
I should have specified that I expected criteria to be a boolean list. Good catch.
3

You can pass a boolean array to loc to indicate which columns should be kept and which not.

For example,

>>> df
    A   B   C   D    E
0  73  15  55  33  foo
1  63  64  11  11  bar
2  56  72  57  55  foo

>>> df.loc[:, [True, True, False, False, True]]
    A   B    E
0  73  15  foo
1  63  64  bar
2  56  72  foo

Comments

1

I'm using this, it's cleaner

comb.values[:,criteria]

credit: https://stackoverflow.com/a/43291257/815677

1 Comment

Just to be clear, this returns an numpy.ndarray, and not a pandas.DataFrame.
-1

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.

4 Comments

There are already proposed solutions which are shorter/less repetitive than the accepted solution but also more elegant.
Seconding @JeanPaul... best to avoid transposes
@william_grisaitis What's the problem with transposes? Are they memory/compute intensive, or do you just find the T aesthetically displeasing, or ...?
@SethJohnson they can be really slow. not an expert, but that's my experience. if i had to guess, it's reallocating memory under the hood for everything (not a zero-copy operation).
-1

Another approach is to use Python's built-in filter function:

def satisfies_criteria(column):
    return comb[column].count() > 4000


cols = filter(satisfies_criteria, df.columns)
df[cols]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.