Skip to content
Advertisement

Send column names that contain a certain string to a list in pandas

I have the following dataframe that contains columns like:

df

        a   b   c   d   a_main   b_main   c_main   d_main
row
row2
row3

I would like the column names that contain _main sent to a list. such as:

collist = ['a_main'  , 'b_main'  , 'c_main'  , 'd_main']

How best could I do that? Thanks very much!

Advertisement

Answer

try via filter() method:

collist=df.filter(like='_main').columns.tolist()

OR

Via boolean masking:

collist=df.columns[df.columns.str.endswith('_main')].tolist()
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement