用特定值填充numpy数组

时间:2020-03-12 11:30:50

标签: python-3.x numpy

我有一个5x5的零数组。 将numpy导入为np

x = np.zeros((5,5)):

[[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]

我想在某些位置填充1:

input=[(2,2),(1,1),(3,4)] :
     [[0. 0. 0. 1. 0.]
     [0. 0. 0. 0. 0.]
     [0. 0. 1. 0. 0.]
     [0. 1. 0. 0. 0.]
     [0. 0. 0. 0. 0.]] 

在给定输入的情况下我该怎么做?

2 个答案:

答案 0 :(得分:0)

x = np.zeros((5,5))
for pair in input:
    x[pair[0]][pair[1]]=1

代码不言自明。

答案 1 :(得分:0)

您可以使用use项目集

[x.itemset(t, 1) for t in input]

在元组中设置位置,最后一个参数是要设置的值