python numpy 数组中元素大于等于0的元素
1 >>> import numpy as np 2 >>> a = np.random.randint(-5, 5, (5, 5)) 3 >>> a 4 array([[-4, -4, -5, 2, 1], 5 [-1, -2, -1, 3, 3], 6 [-1, -2, 3, -5, 3], 7 [ 0, -3, -5, 1, -4], 8 [ 0, 3, 1, 3, -4]]) 9 # 方式一 10 >>> np.maximum(a, 0) 11 array([[0, 0, 0, 2, 1], 12 [0, 0, 0, 3, 3], 13 [0, 0, 3, 0, 3], 14 [0, 0, 0, 1, 0], 15 [0, 3, 1, 3, 0]]) 16 # 方式二 17 >>> (a + abs(a)) / 2 18 array([[0, 0, 0, 2, 1], 19 [0, 0, 0, 3, 3], 20 [0, 0, 3, 0, 3], 21 [0, 0, 0, 1, 0], 22 [0, 3, 1, 3, 0]]) 23 # 方式三 24 >>> b = a.copy() 25 >>> b[b < 0] = 0 26 >>> b 27 array([[0, 0, 0, 2, 1], 28 [0, 0, 0, 3, 3], 29 [0, 0, 3, 0, 3], 30 [0, 0, 0, 1, 0], 31 [0, 3, 1, 3, 0]]) 32 # 方式四 33 >>> np.where(a > 0, a, 0) 34 array([[0, 0, 0, 2, 1], 35 [0, 0, 0, 3, 3], 36 [0, 0, 3, 0, 3], 37 [0, 0, 0, 1, 0], 38 [0, 3, 1, 3, 0]])