如何用NumPy删除只包含0的数组行
Numpy库提供了一个名为numpy.all()的函数,当传递给第一个参数的n-d数组的所有元素都是True时返回True,否则返回False。因此,要确定整个包含0的行可以通过指定axis=1来删除。它将遍历每一行并检查第一个参数中给出的条件。
示例:
data=[[1,2,3]
[0,0,0]
[9,8,7]]
After removing row with all zeroes:
data=[[1,2,3]
[9,8,7]]
示例 1:
步骤:
- 取一个numpy的n-d数组。
- 使用numpy.all()函数删除只包含零的行。
- 打印n-d数组。
import numpy as np
# take data
data = np.array([[1, 2, 3], [0, 0, 0], [4, 5, 6],
[0, 0, 0], [7, 8, 9], [0, 0, 0]])
# print original data having rows with all zeroes
print("Original Dataset")
print(data)
# remove rows having all zeroes
data = data[~np.all(data == 0, axis=1)]
# data after removing rows having all zeroes
print("After removing rows")
print(data)
输出:
示例 2:
步骤:
- 使用numpy.random.choice()方法,在0-10之间取20个随机数。
- 使用reshape()方法,将它们按行和列对齐。
- 明确地将一些行标记为完全为0。
- 移除全部为零的行。
- 打印数据集。
import numpy as np
# take random data
# random.choice(x,y) will pick y elements from range (0,(x-1))
data = np.random.choice(10, 20)
# specify the dimensions of data i.e (rows,columns)
data = data.reshape(5, 4)
# print original data having rows with all zeroes
print("Original Dataset")
print(data)
# make some rows entirely zero
data[1, :] = 0 # making 2nd row entirely 0
data[4, :] = 0 # making last row entirely 0
# after making 2nd and 5th row as 0
print("After making some rows as entirely 0")
print(data)
data = data[~np.all(data == 0, axis=1)]
# data after removing rows having all zeroes
print("After removing rows")
print(data)
输出: