Home > other >  Non-zero distinct elements and indices in an array in Python
Non-zero distinct elements and indices in an array in Python

Time:07-11

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)]]

CodePudding user response:

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]

CodePudding user response:

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)
  • Related