Python增加了特定的矩阵元素

时间:2014-09-02 02:46:40

标签: python numpy

我想识别矩阵中的某些元素(例如,小于4)并将元素增加1000。元素为2,因此该元素更改为1002.如何有效地执行此操作?

import numpy as np

x = np.array([[2,3,4,5],[3,4,5,6],[4,5,6,7],[8,9,10,11]])
x[x <= 4] = x[x = x+1000]

最终x应为np.array([[1002,1003,1004,5],[1003,1004,5,6],[1004,5,6,7],[8,9,10,11]])

1 个答案:

答案 0 :(得分:4)

您可以这样做:

import numpy as np
x = np.array([[2,3,4,5],[3,4,5,6],[4,5,6,7],[8,9,10,11]])
x[x <= 4] += 1000
print x

输出:

[[1002 1003 1004    5]
 [1003 1004    5    6]
 [1004    5    6    7]
 [   8    9   10   11]]