简体   繁体   English

从 numpy ndarray 中删除零行

[英]remove zero rows from numpy ndarray

Given mxn nd array of floats, what is the best way to get an m' xn nd array of floats that does not contain all-zero rows?给定 mxn nd 浮点数组,获得不包含全零行的 m'xn nd 浮点数组的最佳方法是什么?

for example: Given例如:给定

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

I want to get我想得到

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

You can exclude those elements as follows:您可以按如下方式排除这些元素:

>>> 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.]])

Note: @Akavall pointed out correctly that np.abs() would prevent issues with negative values.注意:@Akavall 正确指出np.abs()可以防止出现负值问题。

Additionally, another more complex approach:此外,另一种更复杂的方法:

>>> 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.]])

See: https://www.geeksforgeeks.org/numpy-indexing/参见: https://www.geeksforgeeks.org/numpy-indexing/

You can index using a boolean array:您可以使用 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)])

Here a.any(axis=1) will be True where any elements in the row are non-zero.这里a.any(axis=1)将为True ,其中行中的任何元素都非零。 These are the rows that we want to keep.这些是我们想要保留的行。

A possible solution would be to use the fact that the sum of all zeros is zero.一个可能的解决方案是使用所有零之和为零的事实。 Create a mask using that fact:使用该事实创建一个掩码:

>>> 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.]])

Here's one way to do it:这是一种方法:

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)

This works for arrays containing negative data also.这也适用于包含负数据的 arrays。 If we use sum suppose a row contains [-1, 0, 1] it will be deleted we don't want that.如果我们使用 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