简体   繁体   中英

Non-zero distinct elements and indices in an array in Python

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

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM