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

Pandas混合数据类型列转换为float类型失效问题咨询

问题原因

astype()方法的errors='ignore'参数的生效逻辑是:如果整列转换过程中存在任意一个无法转换为目标类型的值,就会直接放弃整列的转换操作,返回原始数据,所以你运行代码后看不到任何变化。

解决方案

你可以通过pd.to_numeric加掩码替换的方式实现需求,代码如下:

# 先尝试将列转为数值,无法转换的位置设置为NaN
numeric_series = pd.to_numeric(df['mixed'], errors='coerce')
# 将NaN位置的内容替换回原始值
df['mixed'] = numeric_series.where(numeric_series.notna(), df['mixed'])

执行后查看输出即可得到你期望的结果,默认转为float类型,数值部分会带小数点:

df['mixed'].values
array([' GC', 345.0, 69.0, '28-'], dtype=object)

如果需要数值部分保留整数格式,可以使用pandas可空整数类型修改代码:

numeric_series = pd.to_numeric(df['mixed'], errors='coerce').astype('Int64')
df['mixed'] = numeric_series.where(numeric_series.notna(), df['mixed'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:36:04