Drop columns whose name contains a specific string from pandas DataFrame

后端 未结 11 1884
臣服心动
臣服心动 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:11

    You can filter out the columns you DO want using 'filter'

    import pandas as pd
    import numpy as np
    
    data2 = [{'test2': 1, 'result1': 2}, {'test': 5, 'result34': 10, 'c': 20}]
    
    df = pd.DataFrame(data2)
    
    df
    
        c   result1     result34    test    test2
    0   NaN     2.0     NaN     NaN     1.0
    1   20.0    NaN     10.0    5.0     NaN
    

    Now filter

    df.filter(like='result',axis=1)
    

    Get..

       result1  result34
    0   2.0     NaN
    1   NaN     10.0
    
    0 讨论(0)
  • 2020-11-29 17:11

    This method does everything in place. Many of the other answers create copies and are not as efficient:

    df.drop(df.columns[df.columns.str.contains('Test')], axis=1, inplace=True)

    0 讨论(0)
  • 2020-11-29 17:15
    import pandas as pd
    
    import numpy as np
    
    array=np.random.random((2,4))
    
    df=pd.DataFrame(array, columns=('Test1', 'toto', 'test2', 'riri'))
    
    print df
    
          Test1      toto     test2      riri
    0  0.923249  0.572528  0.845464  0.144891
    1  0.020438  0.332540  0.144455  0.741412
    
    cols = [c for c in df.columns if c.lower()[:4] != 'test']
    
    df=df[cols]
    
    print df
           toto      riri
    0  0.572528  0.144891
    1  0.332540  0.741412
    
    0 讨论(0)
  • 2020-11-29 17:18

    Use the DataFrame.select method:

    In [38]: df = DataFrame({'Test1': randn(10), 'Test2': randn(10), 'awesome': randn(10)})
    
    In [39]: df.select(lambda x: not re.search('Test\d+', x), axis=1)
    Out[39]:
       awesome
    0    1.215
    1    1.247
    2    0.142
    3    0.169
    4    0.137
    5   -0.971
    6    0.736
    7    0.214
    8    0.111
    9   -0.214
    
    0 讨论(0)
  • 2020-11-29 17:22

    This can be done neatly in one line with:

    df = df.drop(df.filter(regex='Test').columns, axis=1)
    
    0 讨论(0)
提交回复
热议问题