简体   繁体   English

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

[英]Drop columns whose name contains a specific string from pandas DataFrame

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".我想删除名称中包含“Test”一词的所有列。 The numbers of such columns is not static but depends on a previous function.此类列的数量不是静态的,而是取决于先前的函数。

How can I do that?我该怎么做?

这是执行此操作的一种方法:

df = df[df.columns.drop(list(df.filter(regex='Test')))]
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

Cheaper, Faster, and Idiomatic: str.contains更便宜、更快、更str.containsstr.contains

In recent versions of pandas, you can use string methods on the index and columns.在最新版本的 Pandas 中,您可以在索引和列上使用字符串方法。 Here, str.startswith seems like a good fit.在这里, 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.contains with an SOL anchor:对于不区分大小写的匹配,您可以使用带有 SOL 锚点的str.contains基于正则表达式的匹配:

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=False as well.如果混合类型是可能的,也指定na=False

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

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

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

Use the DataFrame.select method:使用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

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)

Don't drop.不要掉。 Catch the opposite of what you want.抓住你想要的反面。

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

Question states 'I want to drop all the columns whose name contains the word "Test".'问题说明“我想删除名称中包含“测试”一词的所有列。

test_columns = [col for col in df if 'Test' in col]
df.drop(columns=test_columns, inplace=True)

最短的方法是:

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

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 pandas DataFrame 中删除名称包含特定字符串的第一个(或任何第 n 个)列 - Drop the first (or any nth) column whose name contains a specific string from pandas DataFrame 从名称包含特定字符串的列创建新列 - creating new column from columns whose name contains a specific string Python Pandas Dataframe 如果字符串包含特殊字符,则删除列 - Python Pandas Dataframe drop columns if string contains special character 查找名称包含特定字符串的列 - Find column whose name contains a specific string Pandas:如果数据框中的值包含来自另一个数据帧的字符串,则追加列 - Pandas : if value in a dataframe contains string from another dataframe, append columns 检查 pandas dataframe 是否包含项目列表中的特定字符串 - Check if pandas dataframe contains specific string from a list of items 在熊猫数据框中删除特定的multiIndex列 - Drop specific multiIndex columns in a pandas dataframe 如何根据列的值(列的名称不同)从 pandas dataframe 中删除重复的列? - How to drop duplicates columns from a pandas dataframe, based on columns' values (columns don't have the same name)? 如果熊猫数据框中包含特定的子字符串,请替换该字符串 - Replace string in pandas dataframe if it contains specific substring 从Pandas数据框中的特定过滤列集中删除空列 - Drop empty columns from specific set of filtered columns from pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM