【问题标题】:Structured numpy array within a multidimensional array多维数组中的结构化 numpy 数组
【发布时间】:2020-04-08 10:11:30
【问题描述】:

想象一个N x M 维度的numpy 数组。在每个单元格中,它包含一个带有X 元素的结构化数组,每个元素都包含一个x_label

我想访问特定的x_label,因此它返回一个仅包含感兴趣标签值的N x M 数组。

有没有办法做到这一点,而不必使用for 循环(或np.map())函数并创建一个新数组?

例子:

import numpy as np
arr = np.array([[[],[]],
                [[],[]]])

# Each cell contains:
np.array([('par1', 'par2', 'par3')], dtype=[('label_1', 'U10'), ('label_2', 'U10'), ('label3', 'U10')])

我怎样才能得到一个只有 par1 值的 2x2 np.array? 我尝试过不成功:

arr['label_1']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

谢谢!

【问题讨论】:

  • 你的外部数组是什么 dtype?

标签: python arrays numpy multidimensional-array structured-array


【解决方案1】:

我假设你的外部数组是Object dtype,否则应该没有问题:

>>> x = np.array([('par1', 'par2', 'par3')], dtype=[('label_1', 'U10'), ('label_2', 'U10'), ('label3', 'U10')])
>>> Y = np.array(4*[x]+[None])[:-1].reshape(2,2)
>>> Y
array([[array([('par1', 'par2', 'par3')],
      dtype=[('label_1', '<U10'), ('label_2', '<U10'), ('label3', '<U10')]),
        array([('par1', 'par2', 'par3')],
      dtype=[('label_1', '<U10'), ('label_2', '<U10'), ('label3', '<U10')])],
       [array([('par1', 'par2', 'par3')],
      dtype=[('label_1', '<U10'), ('label_2', '<U10'), ('label3', '<U10')]),
        array([('par1', 'par2', 'par3')],
      dtype=[('label_1', '<U10'), ('label_2', '<U10'), ('label3', '<U10')])]],
      dtype=object)

(请注意,我必须跳过箍才能创建这样的东西。)

通过转换为适当的结构化数组让您的生活更轻松:

>>> Z = np.concatenate(Y.ravel()).reshape(Y.shape)
>>> Z
array([[('par1', 'par2', 'par3'), ('par1', 'par2', 'par3')],
       [('par1', 'par2', 'par3'), ('par1', 'par2', 'par3')]],
      dtype=[('label_1', '<U10'), ('label_2', '<U10'), ('label3', '<U10')])

现在,您可以简单地按标签索引:

>>> Z['label_1']
array([['par1', 'par1'],
       ['par1', 'par1']], dtype='<U10')

【讨论】:

  • 谢谢@paul!我自己没有创建数组,这是 Python 包返回函数的方式...我会将数组转换为正确的结构化数组 :-)
  • 关于这个的另一个问题:想象一下数组中的一个值(称为'parX'的参数)是空的。然后,np.concatenate() 将更改初始数组的大小,.np.reshape() 将给出错误ValueError: cannot reshape array of size ### into shape (####)。 @paul 有什么简单的解决方法吗?
  • numpy.lib.recfunctions.stack_arrays(arr.ravel().tolist(),usemask=False).reshape(arr.shape) 可能会起作用。
  • 不幸的是它不起作用。它给出了相同的ValueError...
  • 嗯,抱歉,现在这太复杂了,无法使用 cmets 解决。也许如果该字段为空,您可以将其完全删除(np.lib.recfunctions 中有一个功能,然后再试一次。无论如何,我建议您提出一个新问题,并举例说明您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 2021-12-06
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 2016-07-30
相关资源
最近更新 更多