Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python数组排序和索引_Python_Arrays_Sorting_Numpy - Fatal编程技术网

python数组排序和索引

python数组排序和索引,python,arrays,sorting,numpy,Python,Arrays,Sorting,Numpy,假设您有一个三维阵列: arr = np.zeros((9,9,9)) a[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5)) 如何对该数组中出现的所有值进行排序(而不是像np.sort那样沿轴排序)并显示这些值的所有索引 输出应该类似于: 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

假设您有一个三维阵列:

arr = np.zeros((9,9,9))
a[2:7,2:7,2:7] = np.random.randint(5, size=(5,5,5))
如何对该数组中出现的所有值进行排序(而不是像np.sort那样沿轴排序)并显示这些值的所有索引

输出应该类似于:

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
这或多或少会给你带来你想要的结果;这里的精髓在于分解指数。如果您坚持以按数组值分组的方式获取结果,您可以在stackoverflow中搜索numpy中的分组。

这会起作用(但效率不高):


获取分组值的一个非常简单的方法是
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))

你自己试过什么吗?什么有效,什么无效?我尝试在所有元素上循环,将它们的值和索引放入一个列表,并按值对列表进行排序。但这并不是很有效(我的数据集大约有300x300x300个数组),所以我认为这不值得一提。defaultdict最终是否足够有效?不太有效,我将尝试Eelco的np.unravel_索引方法,看看是否可以绕过分组。。。
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))))
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))