Search code examples
pandasrangematchmultiple-columnsbetween

Get column name in data frame if value is between values


I have a dataframe:

import numpy as np
import pandas as pd

random_number_gen = np.random.default_rng()
df = pd.DataFrame(random_number_gen.integers(-5, 5, size=(1, 13)), columns=list('ABCDEFGHIJKLM'))
A B C D E F G H I J K L M
0 1 4 -4 -1 3 -5 -3 0 -4 -1 3 2

I would like to obtain the names of the columns where a value falls between -1 and 1. I tried this and others:

df.columns[(( -1<= df.any()) & (df.any() <=1)).iloc[0]]

Any help is welcome. Thanks.


Solution

  • If you have a single row:

    df.columns[df.iloc[0].between(-1,1)]
    
    # or
    df.columns[df.squeeze().between(-1,1)]
    

    If you can have multiple rows:

    df.columns[(df.ge(-1)&df.le(1)).any()]
    

    Example output:

    Index(['E', 'G', 'J'], dtype='object')
    

    Used input:

       A  B  C  D  E  F  G  H  I  J  K  L  M
    0  3 -3 -4 -3 -1  3 -1 -5 -2  1  3  2  4