【问题标题】:Creating array with single structured element containing an array使用包含数组的单个结构化元素创建数组
【发布时间】:2020-10-05 15:33:00
【问题描述】:

我有一个像这样的数据类型:

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

如何创建一个包含一个指定 dtype 元素的数组?

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

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

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

对于 np.array 应该能够开箱即用地处理的事情,这似乎是一种不必要的解决方法。

【问题讨论】:

  • 应该是dt = np.dtype([('x', object, 3)])
  • 您创建长度为 1 的元组的一些尝试似乎缺少所需的尾随逗号。试试a = np.array([(['a', 'b', 'c'],)], dtype=dt)
  • 我今天也遇到了同样的任务,我发现的唯一方法是首先创建 np.object_ dtype 的空/零数组,然后为其分配必要的元素。
  • @Arty。我遇到了这个试图回答你之前的问题:)
  • @WarrenWeckesser。我修复了dtype。我将它复制到我的控制台中,意识到我的错误,并且只复制了正确的输出:)

标签: python numpy dtype


【解决方案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,))])

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

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

【讨论】:

  • 知道了。缺少逗号。我几乎想以错字的形式关闭,但答案很好。
  • 我认为你错过了 empty(...)arr, 的分配
猜你喜欢
  • 2016-04-27
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-05
相关资源
最近更新 更多