Skip to main content
 首页 » 编程设计

python之从 np.where 获得的元组的位置处的随机值到矩阵 (np.ndarray)

2025年05月04日17kevingrace

我有一个带有零的矩阵

x=np.array([[1,2,3,0],[4,0,5,0],[7,0,0,0],[0,9,8,0]]) 
>>> x 
array([[1, 2, 3, 0], 
       [4, 0, 5, 0], 
       [7, 0, 0, 0], 
       [0, 9, 8, 0]]) 

并希望随机值只进入一个不为零的位置。我可以从 np.where 获取 (row, col) 位置作为元组

pos = np.where(x!=0) 
>>> (array([0, 0, 0, 1, 1, 2, 3, 3], dtype=int64), array([0, 1, 2, 0, 2, 0, 1, 2], dtype=int64)) 

有没有一种方法可以在 pos 的位置对矩阵 x 使用 np.random(或其他东西)而不改变 where是零吗?

# pseudocode 
new_x = np.rand(x, at pos) 

请您参考如下方法:

我假设您想用随机整数替换非零值。

您可以使用 numpy.place 的组合和 numpy.random.randint功能。

>>> x=np.array([[1,2,3,0],[4,0,5,0],[7,0,0,0],[0,9,8,0]]) 
>>> x 
array([[1, 2, 3, 0], 
       [4, 0, 5, 0], 
       [7, 0, 0, 0], 
       [0, 9, 8, 0]]) 
>>> lower_bound, upper_bound = 1, 5 # random function boundary 
>>> np.place(x, x!=0, np.random.randint(lower_bound, upper_bound, np.count_nonzero(x))) 
>>> x 
array([[2, 2, 3, 0], 
       [1, 0, 3, 0], 
       [2, 0, 0, 0], 
       [0, 4, 3, 0]])