【问题标题】:Use the positions of the values of an array in another array with numpy使用numpy在另一个数组中使用数组值的位置
【发布时间】:2015-08-27 07:43:50
【问题描述】:

我想获取数组中的位置,并想从另一个数组中提取这些位置中的值。 我有两个数组:

Array_1 = (1, 0, 23, 4, 0, 0, 17, 81, 0, 10)
Array_2 = (11, 12, 13, 14, 15, 16, 17, 18, 19, 20)

a, b = numpy.unique(Array_1)

我得到以下信息:a 包含值,b 包含位置。

a = (1, 23, 4, 17, 81, 10)
b = (0, 2, 3, 6, 7, 9)

我想要 Array_2 的值在 Array_1 的位置。换句话说,我想要:

c = (11, 13, 14, 17, 18, 20)

我如何掌握这些价值观?

【问题讨论】:

  • 您的示例中有多个缺陷。 1)numpy.unique 将返回一个唯一值的排序数组,包括0。 2nd) 要获取np.unique 的索引,您必须使用关键字return_index=True

标签: python arrays numpy unique


【解决方案1】:

Numpy 支持向量化索引,见"Integer array indexing". 在实践中,这意味着你可以这样做:

a, b = numpy.unique(Array_1, return_index=True)
c = Array_2[b]

【讨论】:

  • 你确定这行得通吗?它给了我array([12, 11, 14, 20, 17, 13, 18]),除非我最后做错了什么。
  • @Divakar,我正在阅读问题中的文字,但现在我发现其中的示例值很奇怪。在 OP 中 a 未排序且不包括 0。这就是为什么我的答案输出中的顺序不同并且包括12
  • 确实很奇怪。似乎也可以使用Array_2[Array_1!=0] 获得输出。不知道numpy.unique有什么意义。
  • np.unique 返回一个数组的所有 unique 值,因此每个值只出现一次。 Array_2[Array_1!=0] will evaluate at *all* non-zero values in Array_1, which is something entirely different. BTW: To do this sort of slicing, one would need to convert the tuples to np.ndarray`首先...
猜你喜欢
  • 2020-10-10
  • 1970-01-01
  • 2017-01-29
  • 2012-03-06
  • 2020-03-19
  • 2018-12-26
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多