【发布时间】:2017-08-03 12:24:53
【问题描述】:
我从包含 N 唯一值 (product(a.shape) >= N) 的数组 a 开始。
我需要在a 中各个元素的位置从a 中的唯一值的(排序)列表中找到具有索引0 .. N-1 的数组b。
举个例子
import numpy as np
np.random.seed(42)
a = np.random.choice([0.1,1.3,7,9.4], size=(4,3))
print a
将a 打印为
[[ 7. 9.4 0.1]
[ 7. 7. 9.4]
[ 0.1 0.1 7. ]
[ 1.3 7. 7. ]]
唯一值是[0.1, 1.3, 7.0, 9.4],所以需要的结果b是
[[2 3 0]
[2 2 3]
[0 0 2]
[1 2 2]]
(例如,a[0,0] 的值是 7.;7. 的索引为 2;因此是 b[0,0] == 2。)
自从numpy does not have an index function, 我可以使用循环来做到这一点。循环输入数组,如下所示:
u = np.unique(a).tolist()
af = a.flatten()
b = np.empty(len(af), dtype=int)
for i in range(len(af)):
b[i] = u.index(af[i])
b = b.reshape(a.shape)
print b
或循环遍历唯一值如下:
u = np.unique(a)
b = np.empty(a.shape, dtype=int)
for i in range(len(u)):
b[np.where(a == u[i])] = i
print b
我认为,在a 中并非所有值都不同的情况下,第二种循环唯一值的方法已经比第一种更有效;但是,它仍然涉及到这个循环,并且与就地操作相比效率相当低。
所以我的问题是:获取数组b 的最有效方法是什么,其中填充了a 的唯一值的索引?
【问题讨论】:
标签: python arrays numpy indexing