简体   繁体   English

如何使用另一个 numpy 数组中的索引更新 numpy 数组

[英]How can I update a numpy array with index in another numpy array

I have我有

  • an numpy.array a of shape (n1, n2, n3, n4)形状为 (n1, n2, n3, n4) 的 numpy.array a
  • an index array idx of shape (n1, n2, i1)形状为 (n1, n2, i1) 的索引数组idx

what I want to do is like the code below我想做的就像下面的代码

for i in range(n1):
    for j in range(n2):
        for k in range(i1):
            b[i, j, k, :] = a[i, j, idx[i, j, k], :]

if there is a numpy function to achieve this without for loop?如果有一个 numpy function 来实现这个不用for循环?

Using as starting point:使用作为起点:

import numpy as np

n1, n2, n3, n4, i1 = range(2, 7)

a = np.random.randint(10, size=(n1, n2, n3, n4))
idx = np.random.randint(n3, size=(n1, n2, i1))
b = np.zeros_like(a, shape=(n1, n2, i1, n4))

In general you can do the following:一般来说,您可以执行以下操作:

I, J, K = np.ogrid[:n1, :n2, :i1]
b[I, J, K] = a[I, J, idx]

Here the I J and K arrays are the equivalent of the loop variables i j and k .这里的I JK arrays 相当于循环变量i jk Their shapes have to be in agreement with the shape of idx .它们的形状必须与idx的形状一致。

In case b has shape (n1, n2, i1, n4) then you might as well do:如果b的形状为 (n1, n2, i1, n4) 那么你不妨这样做:

I, J, _ = np.ogrid[:n1, :n2, :1]
b = a[I, J, idx]

Or alternatively without ogrid :或者没有ogrid

b = np.take_along_axis(a, idx[...,np.newaxis], axis=2)

Here newaxis is used to insert a length-1 axis to allow broadcasting.这里newaxis用于插入一个长度为 1 的轴以允许广播。 Check out the numpy indexing docs for more info.查看numpy 索引文档以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法通过将多维 numpy 数组与另一个 numpy 数组匹配来找到它的索引? - Is there a way how i can find the index of an multidimensional numpy array by matching it to another numpy array? 如何基于另一个numpy数组过滤numpy数组? - How can I filter a numpy array based on another numpy array? 如何返回numpy数组的索引? - How can I return the index of a numpy array? 如何用另一个numpy数组索引多维numpy数组 - How to index multidimensional numpy array with another numpy array 如何在 python 中用另一个 numpy 数组索引 numpy 数组 - How to index a numpy array with another numpy array in python 使用另一个数组索引numpy数组 - Index a numpy array with another array 如何用在另一个数组中找到的值的索引替换 Python NumPy 数组中的值? - How can I replace values in a Python NumPy array with the index of those values found in another array? 如何用另一个数组中唯一值的索引替换numpy数组中的重复值? - How can I replace recurring values in a numpy array by the index of the unique value from another array? 在 python 和 numpy 中,如何根据两个数组中存在的列从另一个数组更新数组? - In python with numpy, how can I update array from another array depend on column that exists in both? 如何将一个 numpy 数组替换为另一个具有其他维度的 numpy 数组? - How can a numpy array replaced by another numpy array with other dimensions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM