python - 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
........
解决方案
我想不出一个完全没有循环的解决方案,但一个可行的解决方案涉及使用该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])]
推荐阅读
- elasticsearch - 如何计算弹性搜索中大于平均值的最小值?
- python - 如何从结果集中获取值作为浮点数?
- django - 如何将传单地图图层设置为默认选择
- django - 如何使用 Django 智能选择创建链式过滤表单字段
- haxe - 如何在 HaxeFlixel 中关闭碰撞
- angular - 完成for循环后如何完成订阅者?
- asp.net - WebAPI 根据某些条件返回不同类型是不是一个坏主意?
- html - 以嵌入地图为中心的文本存在问题
- r - Shiny 中的 GGplot 不断返回“应使用 `aes()` 或 `aes_()` 创建映射。”
- python - 删除不和谐机器人链接频道ID