python - 如何根据条件选择列?

标签 python pandas

我有 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'c1c2 然后按 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/

相关文章:

python - JSON 和 MySQL 更新查询

c++ - 如何在 PyQt 上使用 Qxt 库?

python - 在 Python 中生成包含 4 列的 1 GB 文件

python - PyCharm 将多个 df 导出到单个 csv 文件

python - 如何创建一个新列,其值是现有 ByteArray 列的十六进制字符串?

python - 将先前数据中的信息分组到向量数据帧中

python - 玛雅Python : Getting a Float Slider Group to align in the same row as Checkboxes

Python - 如何识别 OHLC 数据集中的数字范围?

python - 导入错误 : Missing required dependencies ['numpy' ]

python - 使用 onclick 中的 y 值更新(或重绘?)matplotlib 条形图