numpy:有没有办法从一系列映射创建一个没有外部循环的数组?

时间:2021-03-10 21:23:07

To me, this sounds like a common use-case, but I couldn't find the proper function/thread for it, yet.

对我来说,这听起来像是一个常见的用例,但我找不到适当的函数/线程。

I have two numpy arrays, one is a sequence of triplets and the other the associated sequence of indices. I want to create a 1-dim array of equal sequence length, composed of the mapping items according to their index.

我有两个numpy数组,一个是三元组序列,另一个是相关的索引序列。我想创建一个序列长度相等的1-dim数组,由根据索引的映射项组成。

Example:

例:

mapping = np.array(((25, 120, 240), (18, 177, 240), (0, 0, 0), (10, 120, 285)))
indices = np.array((0, 1, 0, 0))

print "mapping:", mapping
print "indices:", indices
print "mapped:", mapping[indices]

Which produces the following output:

其中产生以下输出:

mapping: [[ 25 120 240]
 [ 18 177 240]
 [  0   0   0]
 [  10 120 285]]
indices: [0 1 0 0]
mapped: [[ 25 120 240]
 [ 18 177 240]
 [ 25 120 240]
 [ 25 120 240]]

Of course, this approach takes the whole mapping array as one mapping, not as a list of mappings, returning only the 1st or 2nd inner mapping, according to the indices array. But what I was looking for is this:

当然,这种方法将整个映射数组作为一个映射,而不是映射列表,根据索引数组仅返回第一个或第二个内部映射。但我正在寻找的是:

mapped: [25 177 0 10]

... which is made from the 1st item of the 1st mapping, the 2nd of the 2nd mapping and the first of the 3rd and 4th mapping.

...由第1映射的第1项,第2映射的第2项以及第3和第4映射的第1项构成。

Is there a lean way to do it with numpy functionality alone, without external looping and without excess of memory usage for temporary arrays?

有没有一种精益的方法来单独使用numpy功能,没有外部循环并且没有超出临时阵列的内存使用量?

1 个解决方案

#1


2  

I think you are looking for this part of numpy's documentation on indexing.

我想你正在寻找关于索引的numpy文档的这一部分。

In [17]: mapping[(np.arange(indices.shape[-1]),indices)]
Out[17]: array([ 25, 177,   0,   10])

This create a temporary array (np.arange) but it is 1-dimensional and I couldn't think of anything better.

这创建了一个临时数组(np.arange),但它是1维的,我想不出更好的东西。

#1


2  

I think you are looking for this part of numpy's documentation on indexing.

我想你正在寻找关于索引的numpy文档的这一部分。

In [17]: mapping[(np.arange(indices.shape[-1]),indices)]
Out[17]: array([ 25, 177,   0,   10])

This create a temporary array (np.arange) but it is 1-dimensional and I couldn't think of anything better.

这创建了一个临时数组(np.arange),但它是1维的,我想不出更好的东西。