首页 > 解决方案 > numpy:内容到索引,索引到内容

问题描述

我的问题是关于 Numpy 数组的索引内容,索引内容。有什么高效优雅的方法吗?

由此(一维,百万值):

a = np.array ([0,1,1,1,3,3,5,1,2,3,6,9,10,....]) 

列出或 ndarray :

output = [[0],[1,2,3,7],[8],[4,5,9],[],[6],[10],[],[],[11],[12],....]

output[0] = value 0 , result:[0]       = locatoin 0 in a 
output[1] = value 1 , result:[1,2,3,7] = location 1 ,2 ,3 , 7 in a
output[2] = value 2 , result:[8] = location 8 
output[3] = value 3 , result:[4,5,9] = location 4,5,9 
output[4] = value 4 , result:[] = location nothing
........

标签: pythonarraysnumpyindexing

解决方案


我想不出一个完全没有循环的解决方案,但一个可行的解决方案涉及使用该where函数。我已经在随机整数列表上对其进行了测试,而且速度非常快。

import numpy as np

a = np.array([0,1,1,1,3,3,5,1,2,3,6,9,10]) 

output = [np.where(a == x)[0] if x in a else [] for x in range(a.min(), a.max())]

在这里你得到output=

[array([0]),
 array([1, 2, 3, 7]),
 array([8]),
 array([4, 5, 9]),
 [],
 array([6]),
 array([10]),
 [],
 [],
 array([11])]

推荐阅读