我有一个具有以下列名的熊猫数据框架:

Result1, Test1, Result2, Test2, Result3, Test3等…

我想删除所有名称包含单词“Test”的列。这些列的数量不是静态的,而是取决于前面的函数。

我该怎么做呢?


当前回答

你可以使用'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

现在过滤器

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

得到. .

   result1  result34
0   2.0     NaN
1   NaN     10.0

其他回答

你可以使用'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

现在过滤器

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

得到. .

   result1  result34
0   2.0     NaN
1   NaN     10.0

这里有一种方法:

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

该方法在适当的位置执行所有操作。许多其他答案会复制,效率不高:

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

使用数据帧。选择方法:

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

删除包含正则表达式的列名列表时的解决方案。我更喜欢这种方法,因为我经常编辑下拉列表。为下拉列表使用负筛选器正则表达式。

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)