[英]Avoiding loops or list comprehension with numpy
是否可以更换
np.concatenate([np.where(x == i)[0] for i in range(y)])
不涉及循环的东西?
我想取一个数组 x,例如 [0, 1, 2, 0 , 2, 2] 和一个数字 y,例如在这种情况下为 2,并输出一个数组 [0, 3, 1, 2, 4, 5 ]。 例如,对于数组中的每个整数,写下它们的索引位置,使它们“按顺序”。
也许某种 numpy 函数可以提高这个列表理解的性能?
这是一种使用argsort
的方法:
# settings
x = np.array([0, 1, 2, 0 , 2, 2])
y = 2
# sort the index
u = np.argsort(x)
# filter those that are larger than y
mask = x[u]<=y
u[mask]
输出:
array([0, 3, 1, 2, 4, 5])
使用argsort会起作用。
numpy.argsort([0, 1, 2, 0 , 2, 2])
=> array([0, 3, 1, 2, 4, 5])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.