📜  如何使用 NumPy 删除仅包含 0 的数组行?

📅  最后修改于: 2022-05-13 01:55:20.571000             🧑  作者: Mango

如何使用 NumPy 删除仅包含 0 的数组行?

Numpy 库提供了一个名为numpy.all()的函数,当传递给第一个参数的 nd 数组的所有元素都为 True 时,该函数返回 True,否则返回 False。因此,可以通过指定axis=1 来确定包含0 的整行。它将遍历每一行并检查第一个参数中给出的条件。

例子:

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 nd 数组。
  • 使用 numpy.all()函数删除仅包含零的行。
  • 打印 nd 数组。
Python3
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)


Python3
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)


输出:

示例 2:

方法如下:

  • 使用 numpy.random.choice() 方法在 0-10 之间取 20 个随机数。
  • 使用 reshape() 方法将它们按行和列对齐。
  • 将某些行显式标记为完全 0。
  • 删除全为零的行。
  • 打印数据集。

蟒蛇3

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)

输出: