Numpy:将一维索引转换为多维索引

发布于 2024-08-18 04:42:36 字数 238 浏览 3 评论 0原文

尽管数组是多维的,但许多数组方法都会返回单个索引。例如:

a = rand(2,3)
z = a.argmax()

对于二维,很容易找到最大元素的矩阵索引:

a[z/3, z%3]

但是对于更多维度,它可能会变得烦人。 Numpy/Scipy 是否有一种简单的方法在给定一个(折叠)维度的索引的情况下返回多个维度的索引?谢谢。

Many array methods return a single index despite the fact that the array is multidimensional. For example:

a = rand(2,3)
z = a.argmax()

For two dimensions, it is easy to find the matrix indices of the maximum element:

a[z/3, z%3]

But for more dimensions, it can become annoying. Does Numpy/Scipy have a simple way of returning the indices in multiple dimensions given an index in one (collapsed) dimension? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

并安 2024-08-25 04:42:36

知道了!

a = X.argmax()
(i,j) = unravel_index(a, X.shape)

Got it!

a = X.argmax()
(i,j) = unravel_index(a, X.shape)
寻找我们的幸福 2024-08-25 04:42:36

我不知道有什么内置函数可以满足您的要求,但是这个函数在哪里
已经出现在我面前,我意识到我真正想做的是:

给定两个具有相同形状的数组 a,b,找到 b 中的元素
与 a 的最大元素相同的位置(相同的 [i,j,k...] 位置)

为此,快速的 numpy-ish 解决方案是:

j = a.flatten().argmax()
corresponding_b_element = b.flatten()[j]

Vince Marchetti

I don't know of an built-in function that does what you want, but where this
has come up for me, I realized that what I really wanted to do was this:

given 2 arrays a,b with the same shape, find the element of b which is in
the same position (same [i,j,k...] position) as the maximum element of a

For this, the quick numpy-ish solution is:

j = a.flatten().argmax()
corresponding_b_element = b.flatten()[j]

Vince Marchetti

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文