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

如何为包含混合类型元素的列表字段定义PyArrow Schema

解决方案:为混合类型列表字段定义PyArrow Schema

你的account_id字段是包含整数和字符串的混合类型一维列表,PyArrow的list_()构造器仅接受单一元素类型作为参数,因此需要用**联合类型(Union Type)**作为列表的元素类型,来兼容不同类型的元素。

正确的Schema定义

直接将列表的元素类型指定为包含整数和字符串的联合类型即可:

pa.field('account_id', pa.list_(pa.union([pa.int64(), pa.string()])))

如果需要更明确地标记联合类型的成员(比如为每个类型添加名称标签),可以使用带字段定义的联合类型:

pa.field('account_id', pa.list_(pa.union(
    [pa.field('account_num', pa.int64()), pa.field('account_name', pa.string())],
    mode='sparse'  # 可选模式,默认是sparse,也可以指定为dense
)))

完整代码示例

以下是从JSON数据转换为PyArrow表的完整流程:

import pyarrow as pa
import pyarrow.json

# 你的JSON数据
json_data = '''
[
  {
    "id": 7654,
    "account_id": [
      17,
      "100.01.001 Cash"
    ]
  }
]
'''

# 定义完整Schema
schema = pa.schema([
    pa.field('id', pa.int64()),
    pa.field('account_id', pa.list_(pa.union([pa.int64(), pa.string()])))
])

# 转换为PyArrow表
table = pa.json.read_json(pa.py_buffer(json_data.encode()), schema=schema)

# 验证结果
print("表结构:")
print(table.schema)
print("\n表数据:")
print(table.to_pandas())

你之前写法的问题说明

  • pa.list_(pa.list_(pa.int64(),pa.string())):错误嵌套list结构,你的account_id是一维列表,不是二维列表
  • pa.list_(pa.int64(), pa.list_(pa.string())):list_()仅接受一个元素类型参数,第二个参数属于非法传参
  • pa.list_(pa.int64(), pa.string()):同样违反list_()的参数规则,无法同时传入两个元素类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:02:37