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

使用Pandas提取包含数字(整数/浮点数)的所有列名

提取Pandas DataFrame中数字类型列的列名

问题分析

你现在需要提取包含整数、浮点数的列名,之前的代码只捕获了整数列,还返回了对应的值,而且用or时触发报错,原因是:

  1. dataframe.loc[0, 条件]返回的是该行符合条件的值,不是列名;
  2. 布尔数组的逻辑判断不能用Python原生的or,要使用Pandas支持的按位或运算符|,且需要给每个条件加括号。

解决方案

方法1:直接筛选数字类型的列(最推荐)

Pandas提供了select_dtypes方法,可以直接指定要保留的类型,然后提取列名:

# 筛选整数和浮点数类型的列,转为列表
numeric_cols = dataframe.select_dtypes(include=['int64', 'float64']).columns.tolist()
print(numeric_cols)
# 输出: ['A', 'B', 'D']

方法2:检查第一行元素的类型(适合列 dtype 为object但实际存数字的场景)

如果你的DataFrame存在列类型是object但实际存储数字的情况,可以通过判断第一行元素的类型来筛选:

numeric_cols = [col for col in dataframe.columns if isinstance(dataframe.loc[0, col], (int, float))]
print(numeric_cols)
# 输出: ['A', 'B', 'D']

修正你之前的代码

如果一定要用你最初的思路(通过dtypes判断),可以这样修改:

# 用按位或`|`连接条件,加括号避免优先级问题,然后取index(即列名)转为列表
numeric_cols = dataframe.loc[0, (dataframe.dtypes == 'int64') | (dataframe.dtypes == 'float64')].index.tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:42:25