How to remove multiple columns that end with same text in Pandas?

前端 未结 5 1609
一生所求
一生所求 2021-01-18 03:56

I\'m trying to remove a group of columns from a dataset. All of the variables to remove end with the text \"prefix\".

I did manage to \"collect\' them into a group

5条回答
  •  囚心锁ツ
    2021-01-18 04:47

    I think you need:

    not_prefix_cols= [col for col in df.columns if not 'prefix' in col]
    df2[not_prefix_cols]
    

    But better is use:

    prefix_cols= [col for col in df.columns if not col.endswith('prefix')]
    print (df[prefix_cols])
    

    Sample:

    import pandas as pd
    
    df = pd.DataFrame({'prefixone' : pd.Series([1, 2, 3, 4]),
                       'twoprefix' : pd.Series([20, 30, 40, 50]),
                       'two1prefix' : pd.Series([20, 30, 40, 50])})
    
    print (df)
       prefixone  two1prefix  twoprefix
    0          1          20         20
    1          2          30         30
    2          3          40         40
    3          4          50         50
    
    prefix_cols= [col for col in df.columns if not col.endswith('prefix')]
    print (df[prefix_cols])
       prefixone
    0          1
    1          2
    2          3
    3          4
    

提交回复
热议问题