Pandas转PyArrow失败:字符串转整数类型转换错误排查
解决PyArrow转换Pandas DataFrame时的混合类型报错问题
问题场景
我有一个包含15000条记录的xlsx文件,需将数据序列化后用于API服务并通过HTTP响应返回。样本数据如下:
account_name | dr_code | cr_code |amount | rate | category A | 12582 | 12582 |5000 |30 | POP B | 55AG98 | 55AG98 |2000 |40 | POP C | 5ER0AB | |5000 |2.2 | POP
执行以下代码时触发报错:
df = pandas.read_excel("file.xlsx", usecols=[0, 1,4,6,7, 8]) b = pyarrow.Table.from_pandas(df, preserve_index=True)
错误信息:
pyarrow.lib.ArrowInvalid : ("Could not convert "55AG98" with type str" : tried to convert to int, 'conversion failed for the column dr_code with type object')
核心问题:当列内数据类型一致时代码可正常运行,但dr_code/cr_code列存在混合类型(数字格式与字符串格式),Pandas读取后将这类列标记为object类型,PyArrow自动推断类型时,因无法将字符串转为整数导致转换失败。
解决方案
方案1:读取Excel时强制指定列类型
读取阶段直接指定dr_code和cr_code为字符串类型,避免Pandas自动推断出混合类型:
import pandas as pd import pyarrow as pa # 定义列类型映射,明确指定目标列为字符串 dtype_map = { "dr_code": str, "cr_code": str } # 读取时应用类型规则 df = pd.read_excel("file.xlsx", usecols=[0, 1,4,6,7, 8], dtype=dtype_map) # 转换为PyArrow Table b = pa.Table.from_pandas(df, preserve_index=True)
方案2:转换DataFrame列类型后再转PyArrow
如果已读取DataFrame,可先将目标列强制转为字符串,空值可按需处理:
import pandas as pd import pyarrow as pa df = pd.read_excel("file.xlsx", usecols=[0, 1,4,6,7, 8]) # 强制转换列类型为字符串 df["dr_code"] = df["dr_code"].astype(str) df["cr_code"] = df["cr_code"].astype(str) # 若需要将转换后的"nan"空值还原为空字符串 df["cr_code"] = df["cr_code"].replace("nan", "") # 转换为PyArrow Table b = pa.Table.from_pandas(df, preserve_index=True)
方案3:PyArrow转换时手动指定Schema
通过pyarrow.Schema定义明确的列类型,让PyArrow按指定规则转换:
import pandas as pd import pyarrow as pa df = pd.read_excel("file.xlsx", usecols=[0, 1,4,6,7, 8]) # 定义与数据匹配的Schema,指定dr_code、cr_code为字符串类型 custom_schema = pa.schema([ ("account_name", pa.string()), ("dr_code", pa.string()), ("amount", pa.int64()), # 根据实际数据调整数值类型 ("rate", pa.float64()), ("category", pa.string()) ]) # 使用指定Schema完成转换 b = pa.Table.from_pandas(df, schema=custom_schema, preserve_index=True)
内容的提问来源于stack exchange,提问作者Shiva Sankar
相关产品推荐
相关产品推荐

