简体   繁体   中英

python array sorting and indexing

Suppose you have a 3D array:

arr = np.zeros((9,9,9))
a[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))

How can you sort all occurring values in this array (not along an axis like with eg np.sort) and show all indices of those values?

Output should be something like:

0 at [0,0,0], [0,1,0], [0,2,1], ...etc.
1 at [5,5,5], [5,7,6], ...etc
2 at [4,5,5], ...etc
3 at ...etc

and so on
import numpy as np
arr = np.zeros((9,9,9))
arr[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))

S = np.sort(arr,axis=None)
I = np.argsort(arr, axis=None)
print np.array([S] + list( np.unravel_index(I, arr.shape))).T

This should give you more or less the result you are looking for; the essence here is in unravel_index. If you insist on obtaining your results in a manner grouped by array value, you can search stackoverflow for grouping in numpy.

A very simple method for getting your grouped values would be defaultdict :

from collections import defaultdict

grouped = defaultdict(list)
for position, v in np.ndenumerate(arr):
    grouped[v].append(position)

for v, positions in grouped.items():
    print('{0} is at {1}'.format(v, positions))

This would work (not very efficient though):

arr = np.zeros((9,9,9))
arr[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))

arr = arr.flatten () # Flatten the array, arr is now a (9 * 9 * 9) vector
arr.sort ()          # Sort the now 1-d array
arr.reshape ((9, 9, 9)) # Reshape it

for i in range(0, 5):
    id = np.array(np.where (arr == i)).T
    print('{} at {}'.format(i, ', '.join(map(str, c))))

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