【问题标题】:numpy structured array with bytes field带有字节字段的 numpy 结构化数组
【发布时间】:2021-05-05 20:41:32
【问题描述】:

我正在尝试构建一个结构化的 numpy 数组,其字段为 named 字节字段(类型为 4b,而不是 unicode)。

import numpy as np 
dtype = np.dtype([('count', 'u8'), ('name', '4b')], align=True)
a = np.asarray([(10, b'test')], dtype=dtype)
print(a.dtype)

我收到错误:

ValueError: invalid literal for int() with base 10: b'test'

现在,如果我将字节字段更改为 unicode,

import numpy as np 
dtype = np.dtype([('count', 'u8'), ('name', 'U4')], align=True)
a = np.asarray([(10, 'test')], dtype=dtype)
print(a.dtype)

这不会导致错误,我会得到输出:

{'names':['count','name'], 'formats':['<u8','<U4'], 'offsets':[0,8], 'itemsize':24, 'aligned':True}

但对我来说这是一个 hack,因为我特别想要字节。

问题:如何在结构化 numpy 数组中获取命名字节字段?

【问题讨论】:

    标签: python python-3.x numpy unicode numpy-ndarray


    【解决方案1】:

    您可以使用S 类型的字符串来处理字节字符串:

    >>> dtype = np.dtype([('count', 'u8'), ('name', 'S4')], align=True)
    >>> a = np.array([(10, b'test')], dtype=dtype)
    >>> a
    array([(10, b'test')],
          dtype={'names':['count','name'], 'formats':['<u8','S4'], 'offsets':[0,8], 'itemsize':16, 'aligned':True})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2016-12-07
      相关资源
      最近更新 更多