首页 > 解决方案 > 不删除尾随零的 NumPy 字节数组

问题描述

如何创建一个不删除尾随零的 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_有效,但序列化不适合我的用例,因为它序列化指针而不是实际的底层字节数组。

标签: pythonnumpyserialization

解决方案


推荐阅读