无法重新创建numpy.array,其中每个元素都有一个numpy.void类型

时间:2014-02-11 19:36:02

标签: python arrays numpy

我一直在寻找如何制作numpy.array的年龄,其中每个元素都有一个numpy.void类型。我需要这样做的原因是从文本文件重新创建具有上面指定的元素类型的numpy.array。然后另一个函数需要该数组。 从搜索我已经尝试了以下给出错误的例子。

>>> import numpy as np 
>>> x = np.array([1,2,4], dtype='V')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a readable buffer object

>>> x=np.array([1,2,3], dtype=np.dtype((void,10)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

为简单起见,也许这样的事情适用于任何dtype:

x = np.array([1,2,4])
x_void = x.view( np.dtype((np.void, x.dtype.itemsize)) )

>>> x_void
array([, , ],
      dtype='|V8')
>>> x_void.dtype
dtype('V8')

数组x实际上是np.int类型,但您只是将其视为void数组。创建一个dtype void数组很难直接创建并产生一些问题,例如:

x = np.zeros(3, dtype=np.dtype((np.void,8)))
>>> x[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected a readable buffer object

您必须执行以下操作:

>>> x[0] = np.array(5).view(np.dtype((np.void,8)))

最好只是将数组视为void,除非你真的知道自己在做什么。