简体   繁体   中英

Having trouble recreating an numpy.array where each element has a type of numpy.void

I have been searching for ages on how to make a numpy.array where each element has a type of numpy.void. The reason I need to do this is to recreate a the numpy.array with the element type specified above from a text file. This array is then needed by another function. from searching i have tried the following examples which have given errors.

>>> 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

Thanks in advance for any help.

Perhaps something like this for simplicity and works on any 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')

The array x is really of type np.int , but you are simply viewing it as a void array. Creating a array of dtype void is difficult to do directly and creates some issues, for example:

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

You would have to do the following:

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

Best to simply view the array as void unless you really know what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM