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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With