从NumPy数组中删除一个值

2024-03-28 21:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试所有只包含NumPy数组中零的行。例如,我想从

n = np.array([[1,2], [0,0], [5,6]])

剩下的是:

np.array([[1,2], [5,6]])

Tags: numpynp数组array
3条回答

如果要删除任何只包含零的行,我能想到的最快方法是:

n = 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的回答)。

我很想知道是否有一个简单有效的NumPy解决方案来解决删除具有特定值的行这一更普遍的问题。

使用cython循环可能是一个快速的解决方案:对于每一行,只要行中的一个元素与to_be_removed中的相应元素不同,就可以停止元素比较。

可以使用^{}删除特定的行或列。

例如:

n = [[1,2], [0,0], [5,6]]

np.delete(n, 1, axis=0)

输出为:

array([[1, 2],
       [5, 6]])

要从numpy表中删除第二行:

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

相关问题 更多 >