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

为何pd.DataFrame.select_dtypes支持float却不匹配int类型?

问题原因解析

这是因为pandas的select_dtypes方法对Python原生类型与numpy数值类型的匹配逻辑存在差异:

  • float的匹配逻辑:传入Python原生的float类型时,pandas会自动将其映射为numpy的np.floating类型族,所有属于该族的numpy浮点类型(比如你的float64列c)都会被匹配到,因此df.select_dtypes(float)能正常返回目标列。

  • int的匹配逻辑:在较新的pandas版本中,传入Python原生的int类型时,pandas会将其映射为pandas可空整数类型(Int64),而非numpy的np.integer类型族。你创建的列a是numpy的int64类型(非可空的原生numpy整数类型),无法被该规则匹配,所以df.select_dtypes(int)返回空DataFrame,df.select_dtypes([int, float])也只会选中float64的列c。

如果想要通过类型族匹配所有整数和浮点列,推荐使用numpy的类型族参数,比如:

import numpy as np
df.select_dtypes([np.integer, np.floating])

这样就能同时选中int64和float64类型的列。

内容的提问来源于stack exchange,提问作者U13-Forward

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:20:26