-2

I have this array in my code however I need to remove the rows that contain zeros (in this case the third row and the fourth). I have tried some options but all without success, can someone suggest something for me to solve this problem?

I leave below the array:

print(AA)
array([[2.40258090e+01, 5.46388441e+00],
       [2.37367092e+01, 1.63425169e+02],
       [0.00000000e+00, 1.56246202e-01],
       [1.68035590e+01, 0.00000000e+00],
       [1.06032437e+01, 6.41505749e+00]])
user220318
  • 11
  • 5
  • Does this answer your question? [How do I delete a row in a numpy array which contains a zero?](https://stackoverflow.com/questions/18397805/how-do-i-delete-a-row-in-a-numpy-array-which-contains-a-zero) – Gino Mempin Feb 17 '21 at 00:54

3 Answers3

2

Value Based:

To filter an array by value, boolean masking can be used as:

a[(a[:,0] != 0) & (a[:,1] != 0)]

This filters array a to keep only rows where values in columns 0 and 1 are not zero; using the bitwise & operator.

Index Based:

With a numpy array, using np.delete will do the trick, as:

np.delete(a, [2,3], axis=0)

where a is the array.

Remember, indexes are zero-based, so the third and fourth rows (axis=0) are indexed as [2,3].

Documentation

S3DEV
  • 8,768
  • 3
  • 31
  • 42
0

So python doesn't have built-in support for arrays. Please use a list.

So to answer your question, let's create a list:

lst =   [[2.40258090e+01, 5.46388441e+00],
        [2.37367092e+01, 1.63425169e+02],
        [0.00000000e+00, 1.56246202e-01],
        [1.68035590e+01, 0.00000000e+00],
        [1.06032437e+01, 6.41505749e+00]]

# Now we filter
filtered_lst = [elem for elem in lst if 0 not in elem]
print(filtered_lst)

output:

[[24.025809, 5.46388441], [23.7367092, 163.425169], [10.6032437, 6.41505749]]

Is that what you wanted?

Luca Sans S
  • 118
  • 8
0

One way to remove the rows with 0s using basic Python

j=1
while j<len(a):
    for i in a[j]:
        if i == 0.0:
            a.remove(a[j])
            j-=1
    j+=1
dododips
  • 91
  • 1
  • 6
  • Code dumps do not make for good answers. You should explain *how* and *why* this solves their problem. I recommend reading, "[How do I write a good answer?"](//stackoverflow.com/help/how-to-answer) – John Conde Feb 17 '21 at 01:16