[英]Fill certain indices of a 3d numpy array
我有一個像這樣的索引列表:
selected_coords = [[1, 8, 30], [15, 4, 6] ,...]
和這樣的值列表:
differences = [1, 5, 8, 2, ...]
兩者都有 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]
如果我在這個循環中打印索引和值,我會得到正確的格式,但是如果我在循環之后打印矩陣,似乎這些值已經被多次放入那里而不是僅僅放在指定的索引上。 我究竟做錯了什么?
您應該盡可能避免在 numpy 數組上循環,否則您將失去性能。 您可以使用高級(“花哨”)索引來索引特定索引處的元素子集。 這會像這樣工作:
brain_map[ind_x, ind_y, ind_z] = vals
其中ind_x, ind_y, ind_z
和vals
都是相同長度的一維數組。 你所擁有的本質上是你的索引數組的轉置:
brain_map[tuple(zip(*selected_coords))] = differences
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.