我有 pandas DataFrame,我想知道如何从给定列表 targets
中选择包含任何子字符串的列:
targets = ["c1", "c2"]
df =
c1_targ c2xxx c3abc
... ... ...
预期结果:
df =
c1_targ c2xxx
... ...
这是我尝试过的:
cols = [[True if col in df.columns else False] for col in targets]
最佳答案
您可以通过 |
将字符串的每个值加入正则表达式 OR
- 'c1|c2'
是 c1
或 c2
然后按 DataFrame.filter
过滤:
targets = ["c1", "c2"]
df1 = df.filter(regex='|'.join(targets))
或通过 str.contains
创建掩码并按 DataFrame.loc
过滤使用 :
通过掩码获取所有行和列:
df1 = df.loc[:, df.columns.str.contains('|'.join(targets))]
print (df1)
c1_targ c2xxx
0 ... ...
关于python - 如何根据条件选择列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57918327/