不删除尾随零的 NumPy 字节数组

时间:2021-02-18 15:28:01

标签: python numpy serialization

如何创建不删除尾随零的 NumPy 字节数组? np.bytes_np.str_ 删除尾随零。 np.void 要求数组的每个元素都具有相同的长度。是否有任何 dtype 可以包含尾随零和可变长度的字节块?

>>> np.array([b'\x00', b'\x01\x00'], np.void)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Invalid type promotion with void datatypes of different lengths. Use the `np.bytes_` datatype instead to pad the shorter value with trailing zero bytes.
>>> np.array([b'\x00', b'\x01\x00'], np.bytes_)
array([b'', b'\x01'], dtype='|S2')
>>> np.array([b'\x00', b'\x01\x00'], np.str_)
array(['', '\x01'], dtype='<U2')
>>> np.array([b'\x00', b'\x01\x00'], np.object_)
array([b'\x00', b'\x01\x00'], dtype=object)

虽然 np.object_ 有效,但序列化不适合我的用例,因为它序列化指针而不是实际的底层字节数组。

0 个答案:

没有答案
相关问题