0

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 e.g. 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
4
  • 1
    Have you tried anything yourself? What worked, what didn't? Commented Jul 23, 2015 at 9:17
  • I tried looping over all elements, putting their values and indices into a list and sorting that list by values. This is not really efficient though (my data sets have about 300x300x300 arrays) so I thought it's not worth mentioning. Commented Jul 23, 2015 at 9:32
  • Was defaultdict efficient enough, in the end? Commented Jul 23, 2015 at 9:50
  • Not really, I will try Eelco's approach with np.unravel_index and see whether I can circumvent grouping... Commented Jul 23, 2015 at 10:11

3 Answers 3

1

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))
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.