我正在尝试从NumPy数组中删除仅包含零的所有行。例如,我想从中删除[0,0]
n = np.array([[1,2], [0,0], [5,6]])
并且最终留下:
np.array([[1,2], [5,6]])
import numpy
n = numpy.array([[1,2],[0,0],[5,6]])
new_n = numpy.delete(n, 1, axis=0)
要删除只包含0的行:
import numpy
n = numpy.array([[1,2],[0,0],[5,6]])
idxs = numpy.any(n != 0, axis=1) # index of rows with at least one non zero value
n_non_zero = n[idxs, :] # selection of the wanted rows
numpy.delete(n, numpy.s_[1], axis=0)
可以简化为 numpy.delete(n, 1)
。此外,numpy.any(n != 0, axis=1)
可以简化为 n.any(axis=1)
。n[idx,:]
可以简单地替换为 n[idx]
。 - Eric O. Lebigotnumpy.delete(n, numpy.s_[1], axis=0)
需要一个轴参数:可以简化为 numpy.delete(n, 1, axis=0)
。 - Eric O. Lebigotn = numpy.array([[1,2], [0,0], [5,6]])
keep_row = n.any(axis=1) # Index of rows with at least one non-zero value
n_non_zero = n[keep_row] # Rows to keep, only
这比Simon的答案运行速度快得多,因为n.any()
一旦遇到任何非零值就停止检查每行的值(在Simon的答案中,先将每行的所有元素与零进行比较,这会导致不必要的计算)。
如果你需要删除具有特定值的行(而不是仅删除只包含零的行),这里是答案的一个泛化:
n = numpy.array([[1,2], [0,0], [5,6]])
to_be_removed = [0, 0] # Can be any row values: [5, 6], etc.
other_rows = (n != to_be_removed).any(axis=1) # Rows that have at least one element that differs
n_other_rows = n[other_rows] # New array with rows equal to to_be_removed removed.
to_be_removed
的第一个元素不匹配,也将比较n
的其余行元素与to_be_removed
的元素(如Simon的答案中所示)。to_be_removed
的相应元素不同,元素比较就可以停止。numpy.delete
来删除特定的行或列。n = [[1,2], [0,0], [5,6]]
np.delete(n, 1, axis=0)
array([[1, 2],
[5, 6]])
[0,0]
元素,而且只有一个。 - user1220022按照值来删除,该值是一个对象。
操作步骤如下:
>>> n
array([[1, 2],
[0, 0],
[5, 6]])
>>> bl=n==[0,0]
>>> bl
array([[False, False],
[ True, True],
[False, False]], dtype=bool)
>>> bl=np.any(bl,axis=1)
>>> bl
array([False, True, False], dtype=bool)
>>> ind=np.nonzero(bl)[0]
>>> ind
array([1])
>>> np.delete(n,ind,axis=0)
array([[1, 2],
[5, 6]])
np.all()
来获取那些精确匹配而不仅仅包含0(即只有[0,0])的元素。 - DarkCygnus