Python 从 Pandas DataFrame 中删除名称包含特定字符串的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19071199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:43:38  来源:igfitidea点击:

Drop columns whose name contains a specific string from pandas DataFrame

pythonpandasdataframe

提问by Alexis Eggermont

I have a pandas dataframe with the following column names:

我有一个带有以下列名称的熊猫数据框:

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

结果 1、测试 1、结果 2、测试 2、结果 3、测试 3 等...

I want to drop all the columns whose name contains the word "Test". The numbers of such columns is not static but depends on a previous function.

我想删除名称中包含“Test”一词的所有列。此类列的数量不是静态的,而是取决于先前的函数。

How can I do that?

我怎样才能做到这一点?

采纳答案by Nic

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

回答by Phillip Cloud

Use the DataFrame.selectmethod:

使用DataFrame.select方法:

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

回答by SAH

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

回答by Bindiya12

Here is a good way to this:

这是一个很好的方法:

df = df[df.columns.drop(list(df.filter(regex='Test')))]

回答by Warren O'Neill

This can be done neatly in one line with:

这可以在一行中巧妙地完成:

df = df.drop(df.filter(regex='Test').columns, axis=1)

回答by cs95

Cheaper, Faster, and Idiomatic: str.contains

更便宜、更快、更惯用: str.contains

In recent versions of pandas, you can use string methods on the index and columns. Here, str.startswithseems like a good fit.

在最新版本的 Pandas 中,您可以在索引和列上使用字符串方法。在这里,str.startswith似乎很合适。

To remove all columns starting with a given substring:

要删除以给定子字符串开头的所有列:

df.columns.str.startswith('Test')
# array([ True, False, False, False])

df.loc[:,~df.columns.str.startswith('Test')]

  toto test2 riri
0    x     x    x
1    x     x    x


For case-insensitive matching, you can use regex-based matching with str.containswith an SOL anchor:

对于不区分大小写的匹配,您可以使用基于正则表达式的匹配和str.containsSOL 锚点:

df.columns.str.contains('^test', case=False)
# array([ True, False,  True, False])

df.loc[:,~df.columns.str.contains('^test', case=False)] 

  toto riri
0    x    x
1    x    x

if mixed-types is a possibility, specify na=Falseas well.

如果混合类型是可能的,也指定na=False

回答by ba0101

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)

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

回答by Roy Assis

Don't drop. Catch the opposite of what you want.

不要掉。抓住你想要的反面。

df = df.filter(regex='^((?!badword).)*$').columns

回答by ZacNt

the shortest way to do is is :

最短的方法是:

resdf = df.filter(like='Test',axis=1)