使用包含数组的单个结构化元素创建数组



我有一个类似的数据类型:

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

一个名为"x"的字段,包含三个指针。我想用这种类型的单个元素构建一个数组:

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

所有这五个语句都会产生相同的错误结果:

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

如果我试图删除内部列表/数组,我会得到一个错误:

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

也发生同样的错误

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

我已经没有可能的组合了。我正在寻找的结果是

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

如何创建具有指定数据类型的一个元素的数组?

到目前为止,我发现的唯一方法是手动分配:

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

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

对于np.array应该能够开箱即用地处理的事情来说,这似乎是一个不必要的变通方法。

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,))])

输入格式应与输出格式匹配。

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,))])

最新更新