【问题标题】:Making a index array from an array in numpy从numpy中的数组制作索引数组
【发布时间】:2012-09-04 04:48:24
【问题描述】:

早安专家,

我有一个包含整数的数组,我有一个列表,其中包含按特殊顺序排序的数组中的唯一值。我想要的是创建另一个数组,该数组将包含 a 数组中每个值的索引。

#a numpy array with integer values
#size_x and size_y: array dimensions of a
#index_list contain the unique values of a sorted in a special order.
#b New array with the index values

for i in xrange(0,size_x):
     for j in xrange(0,size_y):                    
         b[i][j]=index_list.index(a[i][j])

这可行,但需要很长时间才能完成。有更快的方法吗?

非常感谢您的帮助

德语

【问题讨论】:

  • 使用 numpy 排序、精美的索引或任何你需要的东西。 (或者例如 np.unique 及其可选返回)它应该比基于字典的方法快得多。

标签: python arrays list numpy indexing


【解决方案1】:

缓慢的部分是查找

index_list.index(a[i][j])

使用 Python 字典来完成这项任务会快得多,即。而不是

index_list = [ item_0, item_1, item_2, ...]

使用

index_dict = { item_0:0,  item_1:1, item_2:2, ...}

可以使用以下方法创建:

index_dict = dict( (item, i) for i, item in enumerate(index_list) )

【讨论】:

  • Hayden 非常感谢您的帮助,与我的代码相比,它运行良好,运行时间差异很大。最好的问候德语
【解决方案2】:

没有尝试,但由于这是纯 numpy,它应该比基于字典的方法快得多:

# note that the code will use the next higher value if a value is
# missing from index_list.
new_vals, old_index = np.unique(index_list, return_index=True)

# use searchsorted to find the index:
b_new_index = np.searchsorted(new_vals, a)

# And the original index:
b = old_index[b_new_index]

或者,您可以简单地填充 index_list 中的任何整体。


编辑过的代码,完全是错误的(或非常有限)...

【讨论】:

  • 我有一个问题,它适用于 index_list 中的连续值(即 [0,1,2,3] ,当我有非连续值时(即 [0,1,3, 5]它不起作用,请看一下: import numpy as np a = np.random.random((11, 13))*100 a=a.astype(int) list_colors=np.unique(a) print "列表颜色",list_colors new_vals = np.argsort(list_colors) 打印 "新 vals",new_vals b = new_vals[a]
  • 已经重新设计以使用搜索排序...旧代码需要填补漏洞,是的...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2016-04-08
  • 2021-04-17
  • 1970-01-01
  • 2011-10-23
  • 2014-01-15
相关资源
最近更新 更多