0

I have an array A with shape (3,3). I want to identify all non-zero distinct elements and their indices. I present the expected output.

import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])

The expected output is

Distinct=[10,2,20,1.3,30]
Indices=[[(0,0)],[(0,1),(1,0)],[(1,1)],[(1,2),(2,1)],[(2,2)]]

2 Answers 2

3

Not the prettiest option perhaps, but this does the job.

import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])

Distinct=sorted(set(list(np.reshape(A,A.shape[0]*A.shape[1]))))
Distinct = [x for x in Distinct if x!=0]
Indices = [[] for x in Distinct]

for i,x in enumerate(Distinct):
    for j in range(A.shape[0]):
        for k in range(A.shape[1]):
            if x==A[j,k]:
                Indices[i].append((j,k))

Or a numpy solution, taking inspiration from Kilian's solution:

import numpy as np
A=np.array([[10,2,0],[2,20,1.3],[0,1.3,30]])
Distinct = np.unique(A[A!=0])
Indices = [np.argwhere(A==x) for x in Distinct]
Sign up to request clarification or add additional context in comments.

Comments

1

Here you go!

import numpy as np

A = np.array([[10,2,0], [2,20,1.3], [0,1.3,30]])
indices = np.argwhere(A!=0)
distinct = np.unique(A[A!=0])

print(indices)
print(distinct)

2 Comments

The output is [[0 0] [0 1] [1 0] [1 1] [1 2] [2 1] [2 2]] [ 1.3 2. 10. 20. 30. ] which doesn't match the expected output.
Code is a lot more helpful when it is accompanied by an explanation. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your answer and explain how it answers the specific question being asked. See How to Answer.

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.