插入具有已知位置和值的数组

问题描述 投票:0回答:2
import numpy as np

a = np.zeros([2,2])

b = np.array([[0,0],
              [0,1],
              [1,0],
              [1,1]])

values = np.array([[10,20,30,40]]).T

#some function
#desired outcome for a as numpy array:

a = [[10,20],
     [30,40]]

您可以从代码中看到,我有一个零值数组,我想用值填充。我的问题是NumPy是否为此提供任何功能?在使用for循环之前,我想找到一种优雅的方法。谢谢。

python numpy
2个回答
0
投票

简单的方法是使用numpy索引:

import numpy as np

a = np.zeros([2, 2])

b = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

values = np.array([10, 20, 30, 40])

rows, cols = zip(*b)
a[rows, cols] = values
print(a)

输出

[[10. 20.]
 [30. 40.]]

一种替代方法是使用scipy中的csr_matrix构造函数:

import numpy as np
from scipy.sparse import csr_matrix

a = np.zeros([2, 2])

b = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

values = np.array([10, 20, 30, 40])

a = csr_matrix((values, zip(*b)), a.shape).todense()
print(a)

输出

[[10 20]
 [30 40]]

0
投票

一种方法是np.put_along_axis

np.put_along_axis

或者因为np.put_along_axis(a, b, values, 0) 是一个零数组,所以我们也可以使用a。我们只需要修改np.add.at以匹配np.add.at的尺寸即可:

indices

a
© www.soinside.com 2019 - 2024. All rights reserved.