You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中筛选包含字符'c'的列生成新DataFrame

筛选DataFrame中含字符'c'的列

以下是几种高效实现的方法:

方法一:列表推导式筛选列名

遍历DataFrame的所有列名,筛选出包含'c'的列,再用该列列表生成新DataFrame:

import pandas as pd

# 假设原始DataFrame名为df
target_cols = [col for col in df.columns if 'c' in col]
new_df = df[target_cols]

方法二:使用pandas内置的filter方法

pandas的filter方法支持直接按子串匹配列名,代码更简洁:

new_df = df.filter(like='c')

扩展:忽略大小写匹配

如果需要不区分大小写(比如同时匹配'C'和'c'),可以调整实现:

  • 列表推导式版本:
target_cols = [col for col in df.columns if 'c' in col.lower()]
new_df = df[target_cols]
  • filter结合正则版本:
new_df = df.filter(regex='(?i)c')

内容的提问来源于stack exchange,提问作者Drakkar Leon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 08:35:22