【问题标题】:Dump NumPy Array to YAML as regular list将 NumPy 数组作为常规列表转储到 YAML
【发布时间】:2023-02-20 19:11:49
【问题描述】:

当使用 PyYAML 保护 YAML 文件中的 NumPy 数组时,它默认添加大量元数据,以便在加载文件时可以恢复实际数组。例子:

import numpy as np
import yaml

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

结果是

!!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 数组,而是需要生成的 YAML 与其他应用程序兼容。因此,我希望将数组作为正常序列转储,即像这样:

- 1
- 2
- 3

有没有办法告诉 PyYAML 像标准列表一样处理 NumPy 数组,而不必手动转换每个数组?

【问题讨论】:

    标签: python numpy yaml pyyaml


    【解决方案1】:

    这可以通过添加将数组转换为列表的自定义“表示器”来完成:

    import numpy as np
    import yaml
    
    def ndarray_representor(dumper: yaml.Dumper, array: np.ndarray) -> yaml.Node:
        tag = "tag:yaml.org,2002:seq"
        return dumper.represent_sequence(tag, array.tolist())
    
    yaml.add_representer(np.ndarray, ndarray_representor)
    
    a = np.array([1, 2, 3])
    print(yaml.dump(a))
    

    “tag:yaml.org,2002:seq”将其标记为“与语言无关”的序列(参见YAML specification),因此它被转储为一个没有任何附加元数据的简单序列:

    - 1
    - 2
    - 3
    

    【讨论】:

      猜你喜欢
      • 2017-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 2019-08-30
      • 2015-01-07
      • 1970-01-01
      相关资源
      最近更新 更多