Pandas Select DataFrame columns using boolean

后端 未结 5 796
我在风中等你
我在风中等你 2020-12-30 23:05

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

相关标签:
5条回答
  • 2020-12-30 23:25

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

    0 讨论(0)
  • 2020-12-30 23:27

    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.

    0 讨论(0)
  • 2020-12-30 23:28

    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]
    
    0 讨论(0)
  • 2020-12-30 23:28

    I'm using this, it's cleaner

    comb.values[:,criteria]
    

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

    0 讨论(0)
  • 2020-12-30 23:29

    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.

    0 讨论(0)
提交回复
热议问题