Search code examples
pythonpandasdataframepython-re

How to get list of columns from dataframe which start with specific value?


I have df which have different columns and some of them contains list and I want to get all the columns which contains list so I can run function only on them.

df:

Name      Test_Column1        Test_Column2           Test_Column3
A         ['a', 'b']           Test                   ['b']

So ideally i would like to get list of columns ['Test_Column1','Test_Column3']


Solution

  • If want test all columns for lists use DataFrame.applymap:

    cols = df.columns[df.applymap(lambda x: isinstance(x, list)).all()].tolist()
    print (cols)
    ['Test_Column1','Test_Column3']
    

    If want test only first row is possible simplify solution:

    cols = df.columns[df.iloc[0].apply(lambda x: isinstance(x, list))].tolist()