How to delete a string in a numpy array that contains zero?

I am trying to write a function to delete all rows that have a null value. This is not from my code, but an example of an idea that 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 conclusion:

 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 rows with index in b? Sorry, I'm pretty new to this, any help would be greatly appreciated.

+7
source share
4 answers

I am trying to write a function to delete all rows that have a null value.

You do not need to write a function for this, this can be done in one expression:

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

Reading as: select from a all lines that are completely non-zero.

+12
source

It seems that np.delete does not change the array, it just returns a new array, therefore

Instead

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

to try

 a = np.delete(a,zero_row, 0) 
+2
source

I think I found the answer:

as @tuxcanfly said I changed x to a. I also deleted the for loop, because for some reason it deleted the line with index 2.

Instead, now I just decided to delete the rows with b as the delete function using the items in the list to delete the row with this index.

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 conclusion:

 b= [1, 3] a= [[7 1 2 8] [5 8 3 6]] 
+1
source

I think this helps readability (and allows you to loop once rather than twice):

 #!/usr/bin/env python import numpy as np a = np.array(([7,1,2,8], [4,0,3,2], [5,8,3,6], [4,3,2,0])) b = None for row in a: if 0 not in row: b = np.vstack((b, row)) if b is not None else row a = b print 'a = ', a 

In this version, you iterate over each row and check for 0 membership in the row. If the string does not contain zero, you are trying to use np.vstack to add the string to an array named b. If b has not yet been assigned, it is initialized in the current line.

0
source

Source: https://habr.com/ru/post/952343/


All Articles