Python 使用包含数组的单个结构化元素创建数组
我有这样一个数据类型:Python 使用包含数组的单个结构化元素创建数组,python,numpy,dtype,Python,Numpy,Dtype,我有这样一个数据类型: >>> 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'],
>>> 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']
或
对于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,))])
可能应该是
dt=np.dtype([('x',object,3)])
?您创建长度为1的元组的一些尝试似乎缺少所需的跟踪逗号。试试a=np.array([(['a','b','c'],)],dtype=dt)
我今天也遇到了同样的任务,我发现的唯一方法是首先创建np.object\dtype的空/零数组,然后给它分配必要的元素。@Arty。我在回答你之前的问题时遇到了这个问题:)@WarrenWeckesser。我修正了数据类型。我把它复制到我的控制台,意识到我的错误,只复制了正确的输出:)明白了。缺少逗号。我几乎想以打字错误结束,但答案是好的。我想你错过了empty(…)
到arr,
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,))])