Python在numpy数组中用0替换负值
给定numpy数组,任务是将numpy数组中的负值替换为0。让我们看看这个问题的几个例子。
方法#1:Naive Method
# Python code to demonstrate
# to replace negative value with 0
import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print("initial array", ini_array1)
# code to replace all negative value with 0
ini_array1[ini_array1<0] = 0
# printing result
print("New resulting array: ", ini_array1)
输出:
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
方法#2:使用np.where
# Python code to demonstrate
# to replace negative values with 0
import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print("initial array", ini_array1)
# code to replace all negative value with 0
result = np.where(ini_array1<0, 0, ini_array1)
# printing result
print("New resulting array: ", result)
输出:
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
方法#3:使用np.clip
# Python code to demonstrate
# to replace negative values with 0
import numpy as np
# supposing maxx value array can hold
maxx = 1000
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print("initial array", ini_array1)
# code to replace all negative value with 0
result = np.clip(ini_array1, 0, 1000)
# printing result
print("New resulting array: ", result)
输出:
initial array [ 1 2 -3 4 -5 -6]
New resulting array: [1 2 0 4 0 0]
方法4:将给定的数组与一个零数组进行比较,并将两个数组的最大值作为输出写入。
# Python code to demonstrate
# to replace negative values with 0
import numpy as np
ini_array1 = np.array([1, 2, -3, 4, -5, -6])
# printing initial arrays
print("initial array", ini_array1)
# Creating a array of 0
zero_array = np.zeros(ini_array1.shape, dtype=ini_array1.dtype)
print("Zero array", zero_array)
# code to replace all negative value with 0
ini_array2 = np.maximum(ini_array1, zero_array)
# printing result
print("New resulting array: ", ini_array2)
输出:
initial array [ 1 2 -3 4 -5 -6]
Zero array [0 0 0 0 0 0]
New resulting array: [1 2 0 4 0 0]