Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove certain elements from numpy array without destroying the structure

I have a numpy array as below, I want to remove all zeros.

 a = [[ 5  2  0  9  4]
 [ 2  0  9  4  2]
 [ 0  9  4  2  6]
 [ 9  4  2  6  8]
 [ 4  2  6  8  0]
 [ 2  6  8  0  3]
 [ 6  8  0  3 11]
 [ 8  0  3 11  7]
 [ 0  3 11  7  1]
 [ 3 11  7  1  5]
 [11  7  1  5 21]
 [ 7  1  5 21  8]
 [ 1  5 21  8  0]
 [ 5 21  8  0 18]
 [21  8  0 18 12]
 [ 8  0 18 12  3]
 [ 0 18 12  3  9]]

What I want after removing all zeros is as below:

 b = [[ 5  2  9  4]
 [ 2  9  4  2]
 [ 9  4  2  6]
 [ 9  4  2  6  8]
 [ 4  2  6  8]
 [ 2  6  8  3]
 [ 6  8  3 11]
 [ 8  3 11  7]
 [ 3 11  7  1]
 [ 3 11  7  1  5]
 [11  7  1  5 21]
 [ 7  1  5 21  8]
 [ 1  5 21  8]
 [ 5 21  8 18]
 [21  8 18 12]
 [ 8 18 12  3]
 [18 12  3  9]]

I tried a[a>0] but it returned a 1D array: [ 5 2 9 4 2 9 4 2 9 4 2 6 9 4 2 6 8 4 2 6 8 2 6 8 3 6 8 3 11 8 3 11 7 3 11 7 1 3 11 7 1 5 11 7 1 5 21 7 1 5 21 8 1 5 21 8 5 21 8 18 21 8 18 12 8 18 12 3 18 12 3 9]. I wonder is there any command like this a[a>0,axis=1] to remove all the zeros without destroying its structure?

like image 719
Huanian Zhang Avatar asked Feb 20 '26 00:02

Huanian Zhang


1 Answers

The result array cannot be a numpy array, because its shape is not constant. Therefore a possible solution would be doing it the standard pythonic way:

b = [row[row>0] for row in a]
like image 51
kmaork Avatar answered Feb 22 '26 13:02

kmaork



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!