如何通过另一个 np.ndarray 的元素来过滤一个 np.ndarray 的值。

huangapple go评论68阅读模式
英文:

How to filter the values of one np.ndarray by the elements of another

问题

面对使用面具来解决我的算法逻辑问题。

有两个数组。
第一个 - 让我们称之为**"x"**,是二维的。

第二个 - 让我们称之为**"y"**,是一维的,包含了第一个数组的子数组的索引。也就是说,y[i] 是从 x[i] 中要取出的索引。

我使用了标准的Python生成器来实现这个。

import numpy as np
x = np.array([[.55, .45], [0.78, .22], [.85, .15]])
y = np.array([1,0,1])
preds = np.array([x[i, y[i]] for i in range(y.shape[0])])
print(preds) #[0.45, 0.78, 0.15] <- 0.45 == x[0][1], 0.78 == x[1][0], 0.15 == x[2][1] 

然而,这个实现看起来非常复杂。我搜索了NumPy的文档,没有找到类似于我的问题的内容。

当然,你可以从"y"生成一个用于"x"的二维掩码,但是对我来说,实现的速度至关重要,所以这种方法不是一个选择。

你能告诉我在这种情况下该如何继续吗?

英文:

Faced with the problem of using masks for my algorithm's logic.

There are two arrays.
The first - let's call it "x", is two-dimensional.

The second - let's call it "y", is one-dimensional and contains the indices of subarrays of the first one. That is, y[i] is the index to be taken from x[i].

I implemented this using a standard python generator

import numpy as np
x = np.array([[.55, .45], [0.78, .22], [.85, .15]])
y = np.array([1,0,1])
preds = np.array([x[i, y[i]] for i in range(y.shape[0])])
print(preds) #[0.45, 0.78, 0.15] <- 0.45 == x[0][1], 0.78 == x[1][0], 0.15 == x[2][1] 

However, this implementation looks very crusty. I searched through NumPy's documentation and couldn't find anything similar to my question.

Of course, you could generate a 2D mask from "y" for "x", however, speed of implementation is critical to me, so this method is not an option.

Can you tell me how to proceed in this case?

答案1

得分: 0

以下是解决这个问题的一些主题变化:

import numpy as np
x = np.array([[.55, .45], [0.78, .22], [.85, .15]])
y = np.array([1,0,1])
preds = x[np.arange(x.shape[0]), y] 

或者

... # 如前所述
preds = x[np.arange(len(y)), y]

因为 y 必须具有长度 x.shape[0]

或者使用 np.r_[:<slice>]

preds = x[np.r_[:len(y)], y]

这可能更易读,但它是NumPy中不太常见的元素。

英文:

Here are some variations on a theme to solve it:

import numpy as np
x = np.array([[.55, .45], [0.78, .22], [.85, .15]])
y = np.array([1,0,1])
preds = x[np.arange(x.shape[0]), y] 

or

... # as before
preds = x[np.arange(len(y)), y]

since y has to have length x.shape[0].

Or use np.r_[&lt;slice&gt;]:

preds = x[np.r_[:len(y)], y]

which may or may not be more readable (as it's a lesser known element of NumPy).

huangapple
  • 本文由 发表于 2023年2月8日 17:12:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383468.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定