Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a row in a numpy array which contains a zero? [duplicate]

I'm trying to write a function to delete all rows in which have a zero value in. This is not from my code, but an example of the idea I am using:

import numpy as np
a=np.array(([7,1,2,8],[4,0,3,2],[5,8,3,6],[4,3,2,0]))
b=[]

for i in range(len(a)):
    for j in range (len(a[i])):
        if a[i][j]==0:
            b.append(i)

print 'b=', b
for zero_row in b:
    x=np.delete(a,zero_row, 0)

print 'a=',a

and this is my output:

b= [1, 3]
a= [[7 1 2 8]
 [4 0 3 2]
 [5 8 3 6]
 [4 3 2 0]]

How do I get rid of the rows with the index in b? Sorry, I'm fairly new to this any help would be really appreciated.

like image 208
Ashleigh Clayton Avatar asked Aug 23 '13 08:08

Ashleigh Clayton


3 Answers

I'm trying to write a function to delete all rows in which have a zero value in.

You don't need to write a function for that, it can be done in a single expression:

>>> a[np.all(a != 0, axis=1)]
array([[7, 1, 2, 8],
       [5, 8, 3, 6]])

Read as: select from a all rows that are entirely non-zero.

like image 159
Fred Foo Avatar answered Sep 19 '22 13:09

Fred Foo


Looks like np.delete does't change the array, just returns a new array, so

Instead of

x = np.delete(a,zero_row, 0)

try

a = np.delete(a,zero_row, 0)
like image 22
tuxcanfly Avatar answered Sep 19 '22 13:09

tuxcanfly


I think I have found the answer:

as @tuxcanfly said I changed x to a. Also I have now removed the for loop as it removed the row with index 2 for some reason.

Instead I now just chose to delete the rows using b as the delete function with use the elements in the list to remove the row with that index.

the new code:

import numpy as np
a=np.array(([7,1,2,8],[4,0,3,2],[5,8,3,6],[4,3,2,0]))
b=[]

for i in range(len(a)):
    for j in range (len(a[i])):
        if a[i][j]==0:
            b.append(i)
print 'b=',b
for zero_row in b:
    a=np.delete(a,b, 0)

print 'a=',a

and the output:

b= [1, 3]
a= [[7 1 2 8]
 [5 8 3 6]]
like image 28
Ashleigh Clayton Avatar answered Sep 21 '22 13:09

Ashleigh Clayton