如果我有一个多维 numpy 数组,例如:
a = [[0 1 2]
[3 4 5]
[6 7 8]]
如何一步获得某些索引位置的值?例如,如果要定义如下索引对:
indices = [[0,0], [1,1], [2,2]]
我想要:
a[indices] = [0, 4, 8]
请注意,这确实适用于一维数组( Python: How to get values of an array at certain index positions? ),但我不知道如何让它在多维数组中工作。我使用的是 Python 3.7。
最佳答案
正如您链接的一维答案中一样,您可以使用 numpy
在二维中优雅地完成此操作:
a = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
rows, columns = zip([0, 0], [1, 1], [2, 2])
print(a[rows, columns])
print
的输出将是:
array([0, 4, 8])
关于Python:如何获取多维数组在某些索引位置的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079526/