簡體   English   中英

從 numpy ndarray 中刪除零行

[英]remove zero rows from numpy ndarray

給定 mxn nd 浮點數組,獲得不包含全零行的 m'xn nd 浮點數組的最佳方法是什么?

例如:給定

[ 
  [1.0, 0.0, 2.0], 
  [0.0, 0.0, 0.0], 
  [2.0, 1.0, 0.0] 
]

我想得到

[ 
  [1.0, 0.0, 2.0], 
  [2.0, 1.0, 0.0] 
]

您可以按如下方式排除這些元素:

>>> import numpy as np
>>> x = np.array([ [1.0, 0.0, 2.0], [0.0, 0.0, 0.0], [2.0, 1.0, 0.0] ])
>>> x
array([[1., 0., 2.],
       [0., 0., 0.],
       [2., 1., 0.]])
>>> sumrow = np.abs(x).sum(-1)
>>> x[sumrow>0]
array([[1., 0., 2.],
       [2., 1., 0.]])

注意:@Akavall 正確指出np.abs()可以防止出現負值問題。

此外,另一種更復雜的方法:

>>> x = np.array([ [1.0, 0.0, 2.0], [0.0, 0.0, 0.0], [2.0, 1.0, 0.0] ])
>>> x[~np.all(x == 0, axis=1)]
array([[1., 0., 2.],
       [2., 1., 0.]])

參見: https://www.geeksforgeeks.org/numpy-indexing/

您可以使用 boolean 數組進行索引:

a = np.array([[1.0, 0.0, 2.0], [0.0, 0.0, 0.0], [2.0, 1.0, 0.0]])

print(a[a.any(axis=1)])

這里a.any(axis=1)將為True ,其中行中的任何元素都非零。 這些是我們想要保留的行。

一個可能的解決方案是使用所有零之和為零的事實。 使用該事實創建一個掩碼:

>>> bar = np.array ([ [1.0, 0.0, 2.0], [0.0, 0.0, 0.0], [2.0, 1.0, 0.0] ] )
>>> mask = bar.sum(axis=1)==0
>>> bar[mask]
array([[1., 0., 2.],
       [2., 1., 0.]])

這是一種方法:

import numpy as np
x    = np.array([ [1.0, 0.0, 2.0], [0.0, 0.0, 0.0], [2.0, 1.0, 0.0] ])
m, n = x.shape
rows = [row for row in range(m) if not all(x[row] == 0)]
x    = x[rows]
print(x)

這也適用於包含負數據的 arrays。 如果我們使用 sum 假設一行包含 [-1, 0, 1] 它將被刪除,我們不希望這樣。

a=np.array([r for r in a if any(r)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM