2

I have a 2D array, and I hope I can get all of the non-zero data and their position. But now I just can get the non-zero data position.

Is there any way that I can get the value and the position at the same time?

import numpy as np

groupMatrix = np.array([
[1, 1, 0, 0],
[1, 0, 0, 0],
[0, 0, 0, 2],
[3, 3, 0, 2]
])

res = zip(*np.nonzero(groupMatrix))

print(list(res))

The result I got is [(0, 0), (0, 1), (1, 0), (2, 3), (3, 0), (3, 1), (3, 3)]

But I hope the result can show the position with value.

For example, (x, y, z): x, y represent the position and z represents the value at the point.

(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2).

Thank you for your help!!!

1
  • Why use a list comprehension with numpy objects? The whole class is built to avoid doing exactlhy that Commented Feb 15, 2020 at 16:04

3 Answers 3

3

Use np.vstack and numpy multidimensional indexing.

i   = np.nonzero(arr)

res = np.vstack([i, arr[i]])

array([[0, 0, 1, 2, 3, 3, 3],
       [0, 1, 0, 3, 0, 1, 3],
       [1, 1, 1, 2, 3, 3, 2]])

If you really need a list of tuples with the information, you can use list(zip(*...))

>>> list(zip(*res))
[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]
Sign up to request clarification or add additional context in comments.

Comments

2
print(list(zip(*np.nonzero(groupMatrix),groupMatrix[groupMatrix!=0])))

This is certainly not the most efficient solution (it replicates the search for nonzero elements), but it works just fine.

Comments

2

If your arrays are small, like the one in your question, ndenumerate will be readable and fast. If your arrays are large, you should default to vectorized methods.


[(*i, j) for i, j in np.ndenumerate(arr) if j != 0]

[(0, 0, 1), (0, 1, 1), (1, 0, 1), (2, 3, 2), (3, 0, 3), (3, 1, 3), (3, 3, 2)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.