gpt4 book ai didi

python - 从索引、值对填充一个 numpy 数组而不进行迭代

转载 作者:行者123 更新时间:2023-12-04 13:36:09 26 4
gpt4 key购买 nike

我想通过索引将值关联到数组中,而不进行迭代。图片如下,但对于数十万个值:

to_populate = [
[[0, 0], 1],
[[1, 1], 100],
[[2, 3], 29],
[[3, 2], 33],
]

mat = np.empty((4, 4))
mat[:] = np.nan

for idx, val in to_populate:
x, y = idx
mat[x, y] = val

# array([[ 1., nan, nan, nan],
# [ nan, 100., nan, nan],
# [ nan, nan, nan, 29.],
# [ nan, nan, 33., nan]])

我认为它在概念上类似于 np.argwhere 的反向,但具有特定值而不是谓词条件。
mat = np.random.randn(3, 3)

# array([[ 0.89298522, 0.41059024, 0.32770948],
# [-0.91956498, -0.11774805, -1.42625182],
# [ 1.28644586, -0.06951971, -0.88742959]])

np.argwhere(mat < 0)

# array([[1, 0],
# [1, 1],
# [1, 2],
# [2, 1],
# [2, 2]])

最佳答案

您可以“解包”to_populate成行索引、列索引和值,然后使用切片:

import numpy as np
to_populate = [
[[0, 0], 1],
[[1, 1], 100],
[[2, 3], 29],
[[3, 2], 33],
]
# flatten the list
to_populate = np.array([[i[0][0], i[0][1], i[1]] for i in to_populate])

idx = to_populate[:,0]
idy = to_populate[:,1]
values = to_populate[:,2]

mat = np.full((4,4),np.nan)
mat[idx,idy]=values

mat
array([[ 1., nan, nan, nan],
[ nan, 100., nan, nan],
[ nan, nan, nan, 29.],
[ nan, nan, 33., nan]])

关于python - 从索引、值对填充一个 numpy 数组而不进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61913532/

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