max*_*ijn 1 python arrays numpy multidimensional-array matrix-indexing
我有一个像这样的索引列表:
selected_coords = [[1, 8, 30], [15, 4, 6] ,...]
Run Code Online (Sandbox Code Playgroud)
和这样的值列表:
differences = [1, 5, 8, 2, ...]
Run Code Online (Sandbox Code Playgroud)
两者都有 500 个条目。现在我想在正确的索引上用这些值填充一个 3d numpy 数组。我试图做的是以下内容:
brain_map = np.zeros(shape=(48,60,22))
for i, index in enumerate(selected_coords):
ind = list(map(int, index))
brain_map[ind] = differences[i]
Run Code Online (Sandbox Code Playgroud)
如果我在这个循环中打印索引和值,我会得到正确的格式,但是如果我在循环之后打印矩阵,似乎这些值已经被多次放入那里而不是仅仅放在指定的索引上。我究竟做错了什么?
您应该尽可能避免在 numpy 数组上循环,否则您将失去性能。您可以使用高级(“花哨”)索引来索引特定索引处的元素子集。这会像这样工作:
brain_map[ind_x, ind_y, ind_z] = vals
Run Code Online (Sandbox Code Playgroud)
其中ind_x, ind_y, ind_z和vals都是相同长度的一维数组。你所拥有的本质上是你的索引数组的转置:
brain_map[tuple(zip(*selected_coords))] = differences
Run Code Online (Sandbox Code Playgroud)
该zip(*)技巧本质上是对您的列表列表进行转置,然后可以将其作为元组传递以进行索引。例如:
>>> import numpy as np
>>> M = np.random.rand(2, 3, 4)
>>> coords = [[0, 1, 2], [1, 2, 3]]
>>> tuple(zip(*coords))
((0, 1), (1, 2), (2, 3))
>>> M[tuple(zip(*coords))]
array([ 0.12299864, 0.76461622])
>>> M[0, 1, 2], M[1, 2, 3]
(0.12299863762892316, 0.76461622348724623)
Run Code Online (Sandbox Code Playgroud)