擅长:python、mysql、java
<p>如果要删除任何只包含零的行,我能想到的最快方法是:</p>
<pre><code>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
</code></pre>
<p>这比Simon的答案快得多,因为<code>n.any()</code>遇到任何非零值时就停止检查每一行的值(在Simon的答案中,每一行的所有元素都先与零进行比较,这会导致不必要的计算)。</p>
<hr/>
<p>如果您需要删除具有特定值的行(而不是仅删除仅包含零的行),则下面是答案的一般化:</p>
<pre><code>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.
</code></pre>
<p>注意,这个解决方案没有完全优化:即使<code>to_be_removed</code>的第一个元素不匹配,也会将<code>n</code>中的其余行元素与<code>to_be_removed</code>中的行元素进行比较(如Simon的回答)。</p>
<p>我很想知道是否有一个简单有效的NumPy解决方案来解决删除具有特定值的行这一更普遍的问题。</p>
<p>使用<a href="http://docs.cython.org/src/quickstart/cythonize.html" rel="nofollow">cython</a>循环可能是一个快速的解决方案:对于每一行,只要行中的一个元素与<code>to_be_removed</code>中的相应元素不同,就可以停止元素比较。</p>