擅长:python、mysql、java
<p>这段代码足够通用,可以处理您的用例。i、 即使你的行被弄混了。下面给出了两种情况的示例。在</p>
<p>一个按顺序排列行的示例:</p>
<pre><code>In [41]: arr
Out[41]:
array([[ 1, 2, 3, 4, 0, 0, 0, 0],
[ 3, 4, 5, 6, 0, 0, 0, 0],
[ 7, 8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21, 22]])
# extract first half
In [85]: zero_rows = arr[~np.all(arr, axis=1), :]
In [86]: zero_rows
Out[86]:
array([[1, 2, 3, 4, 0, 0, 0, 0],
[3, 4, 5, 6, 0, 0, 0, 0]])
# to trim the trailing zeros in all the rows
In [84]: np.apply_along_axis(np.trim_zeros, 1, zero_rows)
Out[84]:
array([[1, 2, 3, 4],
[3, 4, 5, 6]])
# to extract second half
In [42]: mask_nzero = np.all(arr, axis=1)
In [43]: arr[mask_nzero, :]
Out[43]:
array([[ 7, 8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21, 22]])
</code></pre>
<hr/>
<p>行混合的示例:</p>
^{pr2}$