【问题标题】:Applying numpy take function to 2d array将 numpy take 函数应用于二维数组
【发布时间】:2020-11-26 10:03:20
【问题描述】:

我有以下二维 numpy 数组:

array_a = np.array([[6.2, 2.0, 5.5, 8.0], [6.0, 5.1, 7.1, 8.2], ...])

我还有一个索引列表列表(列表大小不同)代表我想从该数组中选择的值。

wanted_values = [[0,3], [1,2,3], ...]

最后,我想要一个 2d numpy 数组,其中每一行只有与这些索引对应的值。所需的输出如下所示:

np.array([[6.2, 8.0], [5.1, 7.1, 8.2], ...])

我将索引列表转换为 numpy 数组,并警告说“不推荐使用从不规则嵌套序列创建 ndarray”。然后,我将 take 函数应用于 numpy 数组并得到一个错误:

a.take(wanted_values) 
TypeError: Cannot cast array data from dtype('O') to dtype('int64') according to the rule 'safe'

我怎样才能达到预期的效果?有没有更好的方法来解决这个问题?

【问题讨论】:

  • 如果您提供完整的代码示例,我可以运行它并玩弄它;​​)
  • 你不能有一个不规则形状的numpy数组。
  • 删除 numpy,使用列表作为输出
  • 我需要稍后将 argmax 函数应用于每一行,所以最好坚持使用 numpy
  • numpy 不是这样工作的

标签: python numpy numpy-ndarray


【解决方案1】:

从这里开始

[array_a[i][wanted_values[i]] for i in range(len(wanted_values))]

#output

[array([6.2, 8. ]), array([5.1, 7.1, 8.2])]

【讨论】:

    【解决方案2】:

    您的数组中的行大小有问题。考虑下面的例子

    >>> a = np.array([[1],[1,2]])
    <stdin>:1: VisibleDeprecationWarning: Creating an ndarray from ragged nested 
    sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different 
    lengths or shapes) is deprecated. If you meant to do this, you must specify 
    'dtype=object' when creating the ndarray
    

    此外,numpy 函数 take 无法按预期工作。也就是说,给定 numpy 承认的参差不齐的嵌套序列,该函数的作用是:

    1. 它使数组变平,
    2. 它从扁平数组中获取元素,该数组由函数的第二个参数中的数字索引,在您的情况下 wanted_values 并以与它们在 wanted_values 中放置的相同方式放置它们,即您的代码将给出 np.array([6.2, 8.0],[2.0, 5.5, 8.0], ...])这与您的预期不同。

    我建议您将每个选择存储在您构建的同时迭代两个可迭代对象的列表选择中:

    array_a = np.array([[6.2, 2.0, 5.5, 8.0], [6.0, 5.1, 7.1, 8.2]])
    wanted_values = [[0,3], [1,2,3]]
    choice = []
    for xs, indices in zip(array_a, wanted_values):
       choice.append(xs[indices])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 2019-05-07
      • 2019-07-25
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多