python:如果dataframe列与多个子字符串匹配,如何按名称选择该列

python:如果dataframe列与多个子字符串匹配,如何按名称选择该列,python,regex,dataframe,Python,Regex,Dataframe,这是相关的,但与另一个不同 如果列名与多个子字符串条件匹配,我想按名称选择列 我试着使用和操作ie& spike_cols = [col for col in df.columns if ('spike') & ('hey') in col] 这样我就可以准确地得到一列“嘿,斯派克” 我也用过 dfnew = df.filter(regex='spike'&'hey') 获取错误 TypeError:&:'str'和'str'的操作数类型不受支持 这里有一个没有regex的方

这是相关的,但与另一个不同

如果列名与多个子字符串条件匹配,我想按名称选择列

我试着使用和操作ie&

spike_cols = [col for col in df.columns if ('spike') & ('hey') in col]
这样我就可以准确地得到一列“嘿,斯派克” 我也用过

dfnew = df.filter(regex='spike'&'hey')
获取错误

TypeError:&:'str'和'str'的操作数类型不受支持

这里有一个没有regex的方法,只需使用中的
检查子字符串条件:

df[[col for col in df.columns if 'hey' in col and 'spike' in col]]

或者,如果要使用正则表达式,可以执行以下操作:

df.filter(regex='(?=.*hey)(?=.*spike)')


对不起,您是在说:
df.loc[:,df.columns.str.contains('spike | hey')]
?或者事实上:
df.filter(regex='spike | hey')
?@EdChum并不是在寻找一个或多个or解决方案。我正在寻找一个合适的条件。谢谢,我的第一个问题。我还使用了您的答案来修改它,以便在正则表达式中使用变量。类似于df.filter(regex='(?=.*'+a+')(?=.*'+b+'))
df.filter(regex='(?=.*hey)(?=.*spike)')