Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get the position of the nonzero values in a numpy array?

I'm using np.nonzero() and i dont understand the return

I try

for groupPosition in np.nonzero(groupMatrix):
    print groupPosition

and return [0 0 1 2 3 3 3]

for groupPosition in zip(np.nonzero(groupMatrix)):
    print groupPosition

and return (array([0, 1, 0, 3, 0, 1, 3]),)

groupMatrix:

[[ 1.  1.  0.  0.]
[ 1.  0.  0.  0.]
[ 0.  0.  0.  2.]
[ 3.  3.  0.  2.]]

But don't return the position like a (0, 0)

like image 377
user2997534 Avatar asked Jan 12 '23 21:01

user2997534


2 Answers

>>> import numpy as np
>>>
>>> groupMatrix = np.array([
...     [1, 1, 0, 0],
...     [1, 0, 0, 0],
...     [0, 0, 0, 2],
...     [3, 3, 0, 2]
... ])
>>> np.nonzero(groupMatrix)
(array([0, 0, 1, 2, 3, 3, 3], dtype=int64), array([0, 1, 0, 3, 0, 1, 3], dtype=int64))
>>> zip(np.nonzero(groupMatrix))
[(array([0, 0, 1, 2, 3, 3, 3], dtype=int64),), (array([0, 1, 0, 3, 0, 1, 3], dtype=int64),)]

Use zip(*...):

>>> zip(*np.nonzero(groupMatrix))
[(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

zip(*a) is like zip(a[0], a[1], ...)

>>> a = [(0, 1, 2), (3, 4, 5)]
>>> zip(a)
[((0, 1, 2),), ((3, 4, 5),)]
>>> zip(a[0], a[1])
[(0, 3), (1, 4), (2, 5)]
>>> zip(*a)
[(0, 3), (1, 4), (2, 5)]

See Unpacking Argument Lists.

like image 62
falsetru Avatar answered Feb 02 '23 19:02

falsetru


Try the following:

import numpy as np

var = [
    [1.0, 1.0, 0.0, 0.0],
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 0.0, 2.0],
    [3.0, 3.0, 0.0, 2.0]
]

rows, cols = np.nonzero(var)

for r, c in zip(rows, cols):
    print var[r][c]

Returns:

1.0
1.0
1.0
2.0
3.0
3.0
2.0

You are getting the results you are getting because np.nonzero returns a tuple, since your array has 2 dimensions, it has two arrays. Now, each of these arrays need to be used together, so in my example, the function returns the row number, and then the column number. Lets have a look see:

>>> import numpy as np
>>> var = [
    [1.0, 1.0, 0.0, 0.0],
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 0.0, 2.0],
    [3.0, 3.0, 0.0, 2.0]
]
>>>                 
>>> non_zeroes = np.nonzero(var)
>>> non_zeroes
(array([0, 0, 1, 2, 3, 3, 3]), array([0, 1, 0, 3, 0, 1, 3]))

If we take a close look, we can see that var[0][0] is indeed non zero. so is var[3][3]. However, you will not see a 2 in the first tuple and another 2 at the corresponding index.

like image 27
Games Brainiac Avatar answered Feb 02 '23 19:02

Games Brainiac