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

如何让PyYAML将NumPy数组以普通列表格式写入YAML?

问题描述

使用PyYAML保存NumPy数组到YAML文件时,默认会生成大量用于还原数组的元数据,示例代码如下:

import numpy as np
import yaml

a = np.array([1, 2, 3])
print(yaml.dump(a))

执行后输出的YAML内容包含大量Python/NumPy相关的元数据:

!!python/object/apply:numpy.core.multiarray._reconstruct
args:
- !!python/name:numpy.ndarray ''
- !!python/tuple
  - 0
- !!binary |
  Yg==
state: !!python/tuple
- 1
- !!python/tuple
  - 3
- !!python/object/apply:numpy.dtype
  args:
  - i8
  - false
  - true
  state: !!python/tuple
  - 3
  - <
  - null
  - null
  - null
  - -1
  - -1
  - 0
- false
- !!binary |
  AQAAAAAAAAACAAAAAAAAAAMAAAAAAAAA

但实际需求不需要还原精确的NumPy数组,只希望生成兼容其他应用的普通序列格式,比如:

- 1
- 2
- 3

请问能否无需手动转换每个数组,让PyYAML像处理标准列表一样处理NumPy数组?

解决方案

可以通过为NumPy数组注册自定义的YAML表示器实现,无需手动逐个转换数组,具体步骤如下:

  1. 定义转换函数,将NumPy数组转换为普通Python列表
  2. 使用yaml.add_representer为numpy.ndarray类型注册该表示器

示例代码:

import numpy as np
import yaml

# 定义转换函数:将numpy数组转为列表
def numpy_array_representer(dumper, array):
    return dumper.represent_list(array.tolist())

# 为numpy.ndarray类型注册表示器
yaml.add_representer(np.ndarray, numpy_array_representer)

# 测试
a = np.array([1, 2, 3])
print(yaml.dump(a))

执行后输出的YAML内容就是普通序列格式:

- 1
- 2
- 3

如果需要处理NumPy标量类型(如np.int64、np.float64),可以额外注册对应的表示器,示例:

# 处理NumPy标量类型
def numpy_scalar_representer(dumper, scalar):
    return dumper.represent_data(scalar.item())

yaml.add_representer(np.int64, numpy_scalar_representer)
yaml.add_representer(np.float64, numpy_scalar_representer)

这样PyYAML会自动将所有NumPy数组和标量转换为普通Python数据类型,生成兼容其他应用的YAML内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 12:10:23