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

如何将Pandas DataFrame中带双引号的数值串转为int/float类型

类型转换问题解决方案

问题本质

你创建的DataFrame中,所有数值列的字符串外层都包裹了多余的双引号,例如duration列的实际值为'"467900"'(字符串本身带引号),而非普通的数值字符串'467900',因此直接转换类型会报错。

解决步骤

首先需要清除目标列字符串首尾的双引号,再执行类型转换即可,推荐使用pd.to_numeric方法,相比astype容错性更高:

import pandas as pd

# 1. 批量清除所有待转换列首尾的双引号
convert_cols = ["duration", "realtime", "cpu"]
df[convert_cols] = df[convert_cols].apply(lambda col: col.str.strip('"'))

# 2. 转换整数类型列
df["duration"] = pd.to_numeric(df["duration"], downcast="integer")
df["realtime"] = pd.to_numeric(df["realtime"], downcast="integer")

# 3. 转换浮点类型列
df["cpu"] = pd.to_numeric(df["cpu"], downcast="float")

补充说明

  • 如果需要排查脏数据,可以在pd.to_numeric中添加参数errors="coerce",转换失败的异常值会被自动设为NaN,后续可针对性处理:
    df["duration"] = pd.to_numeric(df["duration"], downcast="integer", errors="coerce")
    
  • 之前直接用replace失效的大概率原因是没有使用字符串访问器,正确的全局替换写法为df["duration"] = df["duration"].str.replace('"', ''),但用strip仅清除首尾字符,安全性更高,不会误删内容内部的引号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:36:03