Reputation: 860
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?
Upvotes: 3
Views: 1544
Reputation: 8569
It seems you want to remove zeros if there's exactly the same numbers of zeros in each column. Note, in your example this is not (yet) possible.
b=np.hstack([y.reshape((len(y),1)) for y in [x[x>0] for x in [a[:,i] for i in range(a.shape[1])]]])
Upvotes: 1
Reputation: 6012
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]
Upvotes: 2