简体   繁体   English

使用 numpy 避免循环或列表理解

[英]Avoiding loops or list comprehension with numpy

Is it possible to replace是否可以更换

np.concatenate([np.where(x == i)[0] for i in range(y)])

with something that doesn't involve looping?不涉及循环的东西?

I want to take an array x, eg [0, 1, 2, 0 , 2, 2], and a number y, eg 2 in this case, and output an array [0, 3, 1, 2, 4, 5].我想取一个数组 x,例如 [0, 1, 2, 0 , 2, 2] 和一个数字 y,例如在这种情况下为 2,并输出一个数组 [0, 3, 1, 2, 4, 5 ]。 Eg for each integer in the array, write their index locations such that they're "in order".例如,对于数组中的每个整数,写下它们的索引位置,使它们“按顺序”。

Perhaps some kind of numpy function that can provide a performance boost over this list comprehension?也许某种 numpy 函数可以提高这个列表理解的性能?

Here's an approach that uses argsort :这是一种使用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]

Output:输出:

array([0, 3, 1, 2, 4, 5])

Using argsort would work.使用argsort会起作用。

numpy.argsort([0, 1, 2, 0 , 2, 2])
=> array([0, 3, 1, 2, 4, 5])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM