操纵numpy matrices ..替换一个值

时间:2015-01-18 19:03:29

标签: python numpy

我最近发现了numpy及其在矩阵方面的用处。还有一件事让我感到困扰。如何使用所需的值替换矩阵中的特定值。我试过>

matrix1 = np.zeros([10,10])
replacewith = 1
atposition = np.array(5,5)
matrix1[atposition] = replacewith

所以我要做的就是用1替换中间的0。 谢谢!

1 个答案:

答案 0 :(得分:5)

import numpy as np
matrix1 = np.zeros([10,10])
replacewith = 1
atposition = (5,5)
matrix1[atposition] = replacewith
print matrix1

输出:

[[ 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.  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.]
 [ 0.  0.  0.  0.  0.  1.  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.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]