gpt4 book ai didi

python - 填充 3d numpy 数组的某些索引

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:44 24 4
gpt4 key购买 nike

我有一个这样的索引列表:

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 数组上循环,否则您会损失性能。您可以使用 advanced ("fancy") indexing索引特定索引处的元素子集。这将像这样工作:

brain_map[ind_x, ind_y, ind_z] = vals

其中 ind_x、ind_y、ind_zvals 都是相同长度的一维数组。您所拥有的本质上是索引数组的转置:

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)

关于python - 填充 3d numpy 数组的某些索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com