时间:2021-01-15 11:12:00 | 栏目:Python代码 | 点击:次
如下所示:
>>> import numpy as np >>> a = np.random.randint(-5, 5, (5, 5)) >>> a array([[-4, -4, -5, 2, 1], [-1, -2, -1, 3, 3], [-1, -2, 3, -5, 3], [ 0, -3, -5, 1, -4], [ 0, 3, 1, 3, -4]]) # 方式一 >>> np.maximum(a, 0) array([[0, 0, 0, 2, 1], [0, 0, 0, 3, 3], [0, 0, 3, 0, 3], [0, 0, 0, 1, 0], [0, 3, 1, 3, 0]]) # 方式二 >>> (a + abs(a)) / 2 array([[0, 0, 0, 2, 1], [0, 0, 0, 3, 3], [0, 0, 3, 0, 3], [0, 0, 0, 1, 0], [0, 3, 1, 3, 0]]) # 方式三 >>> b = a.copy() >>> b[b < 0] = 0 >>> b array([[0, 0, 0, 2, 1], [0, 0, 0, 3, 3], [0, 0, 3, 0, 3], [0, 0, 0, 1, 0], [0, 3, 1, 3, 0]]) # 方式四 >>> np.where(a > 0, a, 0) array([[0, 0, 0, 2, 1], [0, 0, 0, 3, 3], [0, 0, 3, 0, 3], [0, 0, 0, 1, 0], [0, 3, 1, 3, 0]])