Creating array with single structured element containing an array

故事扮演 提交于 2021-01-28 07:51:32

问题


I have a dtype like this:

>>> dt = np.dtype([('x', object, 3)])
>>> dt
dtype([('x', 'O', (3,))])

One field named 'x', containing three pointers. I would like to construct an array with a single element of this type:

>>> a = np.array([(['a', 'b', 'c'])], dtype=dt)
>>> b = np.array([(np.array(['a', 'b', 'c'], dtype=object))], dtype=dt)
>>> c = np.array((['a', 'b', 'c']), dtype=dt)
>>> d = np.array(['a', 'b', 'c'], dtype=dt)

>>> e = np.array([([['a', 'b', 'c']])], dtype=dt)

All five of these statements yield the same incorrect result:

array([[(['a', 'a', 'a'],), (['b', 'b', 'b'],), (['c', 'c', 'c'],)]],
      dtype=[('x', 'O', (3,))])

If I try to drop the inner list/array, I get an error:

>>> f = np.array([('a', 'b', 'c')], dtype=dt)
ValueError: could not assign tuple of length 3 to structure with 1 fields.

Same error happens for

>>> g = np.array(('a', 'b', 'c'), dtype=dt)

I've run out of possible combinations to try. The result I am looking for is

 array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])

How do I create an array that has one element of the specified dtype?

So far, the only approach that I've found is manual assignment:

z = np.empty(1, dtype=dt)
z['x'][0, :] = ['a', 'b', 'c']

OR

z[0]['x'] = ['a', 'b', 'c']

This seems like an unnecessary workaround for something that np.array ought to be able to handle out of the box.


回答1:


In [44]: dt = np.dtype([('x', object, 3)])   # corrected
In [45]: dt
Out[45]: dtype([('x', 'O', (3,))])
In [46]: np.empty(3, dt)
Out[46]: 
array([([None, None, None],), ([None, None, None],),
       ([None, None, None],)], dtype=[('x', 'O', (3,))])
In [47]: np.array([(['a','b','c'],)], dt)
Out[47]: array([(['a', 'b', 'c'],)], dtype=[('x', 'O', (3,))])

Input formatting should match output formatting.

In [48]: arr = np.empty(3, dt)
In [49]: arr['x']
Out[49]: 
array([[None, None, None],
       [None, None, None],
       [None, None, None]], dtype=object)
In [50]: arr['x'][0]
Out[50]: array([None, None, None], dtype=object)
In [51]: arr['x'][0] = ['a','b','c']
In [52]: arr
Out[52]: 
array([(['a', 'b', 'c'],), ([None, None, None],), ([None, None, None],)],
      dtype=[('x', 'O', (3,))])


来源:https://stackoverflow.com/questions/64211744/creating-array-with-single-structured-element-containing-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!