【问题标题】:Numpy index nested array with indices from another arrayNumpy 索引嵌套数组,其中包含来自另一个数组的索引
【发布时间】:2020-03-29 11:20:16
【问题描述】:

我有一个像这样的 numpy 数组:

u = np.arange(10).reshape(5, 2)

array([[0, 1],
   [2, 3],
   [4, 5],
   [6, 7],
   [8, 9]])

我有第二个数组,比如

a = np.array([1,0,0,1,0])

我想使用 a 中的值来索引 u 的子数组。 E.g. a[0] is 1, so we chose u[0,1], a[1] is 0, so we choose u[1, 0] 等等。

我已经尝试了很多东西,并且想在没有 for 循环的情况下做到这一点。即使在阅读了numpys indexing guide 之后,我也没有真正找到如何去做。

我尝试过但失败的事情:

>>> u[:, [0,0,1,0,1]]
array([[0, 0, 1, 0, 1],
   [2, 2, 3, 2, 3],
   [4, 4, 5, 4, 5],
   [6, 6, 7, 6, 7],
   [8, 8, 9, 8, 9]])

u[[True, False, True, True, True]]
array([[0, 1],
   [4, 5],
   [6, 7],
   [8, 9]])

最后为了消除混淆,这是我想要的,但是使用 python 循环:

>>> x = []
>>> ct = 0
>>> for i in u:
        x.append(i[a[ct]])
        ct += 1

>>> x
[1, 2, 4, 7, 8]

提前致谢。

【问题讨论】:

  • 你的预期输出是什么?
  • [1, 2, 4, 7, 8] 对于给定的 u 和 a
  • 字典是你的朋友。它有很多种口味。我想推荐使用熊猫(geeksforgeeks.org/python-pandas-dataframe-to_dict)。只需学习一次,每次需要类似功能时,您的生活都会变得更好。
  • @Leos313 我坚信优雅的 numpy 解决方案可以解决我的问题,所以我想避免使用 pandas 和字典。
  • 没错,但正如您所看到的,@Dani Mesejo 的答案提供了一个非常简单直观的解决方案,这对我来说似乎比在我的项目的某些算法中使用 pandas 数据帧更有吸引力甚至完全使用熊猫。不过感谢您的回答!

标签: python arrays numpy indexing


【解决方案1】:

用途:

import numpy as np

u = np.arange(10).reshape(5, 2)
a = np.array([1, 0, 0, 1, 0])
r, _ = u.shape  # get how many rows to use in np.arange(r)

print(u[np.arange(r), a])

输出

[1 2 4 7 8]

有关索引的更多信息,您可以阅读documentation,此article 可能会有所帮助。

【讨论】:

  • 不错!所以它本质上是 u[[0,1,2,3,4],[1,0,0,1,0]]。如果我可能会问,您将这种类型的索引称为什么? IE。在 numpy 文档中哪里可以找到更多相关信息?
  • @charel-f 称为高级索引。
猜你喜欢
  • 2018-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 2016-03-09
  • 2018-10-25
  • 1970-01-01
  • 2020-06-11
相关资源
最近更新 更多