我想识别矩阵中的某些元素(例如,小于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]])
答案 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]]