Drop columns whose name contains a specific string from pandas DataFrame

后端 未结 11 1968
臣服心动
臣服心动 2020-11-29 16:19

I have a pandas dataframe with the following column names:

Result1, Test1, Result2, Test2, Result3, Test3, etc...

I want to drop all the columns whose name c

11条回答
  •  难免孤独
    2020-11-29 17:10

    Solution when dropping a list of column names containing regex. I prefer this approach because I'm frequently editing the drop list. Uses a negative filter regex for the drop list.

    drop_column_names = ['A','B.+','C.*']
    drop_columns_regex = '^(?!(?:'+'|'.join(drop_column_names)+')$)'
    print('Dropping columns:',', '.join([c for c in df.columns if re.search(drop_columns_regex,c)]))
    df = df.filter(regex=drop_columns_regex,axis=1)
    

提交回复
热议问题