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

使用Pandas读取CSV时多数据类型转换失败的技术问询

问题

清洗销售数据时,无法将Price(价格)、Credit Qty(信用数量)、Credit Total(信用总额)列正确转换为float或integer数据类型。

尝试方案
  • 编写移除$和,的转换器函数,报错:cannot convert string to float ""
  • 使用pd.to_numeric(),表面上Price列转为float类型,但所有条目均显示NaN
预期目标
  • 将['Price', 'Credit Qty', 'Credit Total']列的 dtype 转换为float,以支持数学运算
  • 已知Price列最后两行是NaN,且CSV文件最后一行是PowerBI仪表板导出的筛选条件文本
  • 要求在read_csv()参数内完成所有必要的数据类型转换
现有代码
def convert_currency(val):
    new_val = val.replace(',','').replace('$', '')
    return float(new_val)

df = pd.read_csv("file_name.csv", na_values = [''],
           dtype={'Price': convert_currency,
                  'Credit Qty': lambda x: pd.to_numeric(x, errors='coerce', downcast = "float"),
                  'Credit Total': convert_currency)
                     })
df.dtypes
解决方案

你的问题根源在于:

  1. dtype参数不支持自定义转换函数,需改用converters参数
  2. 转换器函数未处理空值、无效文本的情况
  3. 原代码存在语法错误

修正后的代码如下:

import pandas as pd

def convert_currency(val):
    # 处理空值或空白内容
    if pd.isna(val) or val.strip() == '':
        return float('nan')
    # 移除货币符号和千分位分隔符
    cleaned_val = val.replace(',', '').replace('$', '').strip()
    # 捕获无法转换的无效文本(如最后一行筛选内容)
    try:
        return float(cleaned_val)
    except ValueError:
        return float('nan')

df = pd.read_csv(
    "file_name.csv",
    na_values=[''],
    converters={
        'Price': convert_currency,
        'Credit Qty': lambda x: pd.to_numeric(x.strip(), errors='coerce', downcast="float"),
        'Credit Total': convert_currency
    },
    # 跳过最后一行无效的筛选文本,需指定python引擎
    skipfooter=1,
    engine='python'
)

print(df.dtypes)

核心修改说明

  • 替换参数:用converters替代dtype,该参数支持为指定列绑定自定义转换函数
  • 健壮性处理:转换器函数增加空值判断和异常捕获,避免因无效文本导致转换失败
  • 跳过无效行:通过skipfooter=1直接忽略CSV末尾的PowerBI筛选文本
  • 细节优化:给Credit Qty的转换逻辑加上strip(),处理内容前后的空格
  • 修复语法错误:闭合Credit Total对应的括号

完成后,目标列会正确转为float类型,空值和无效内容将被转为NaN,可直接进行后续数学运算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:40:32