如何使用Python中的条件过滤NumPy数组

3

我正在使用我的numpy数组v进行如下操作,以删除小于等于1的元素,然后选择numpy数组中前3个元素的索引。

 for ele in v.toarray()[0].tolist():
        if ele <= 1:
            useless_index = v.toarray()[0].tolist().index(ele)
            temp_list.append(useless_index)

 #take top 3 words from each document
 indexes =v.toarray()[0].argsort()[-3:]
 useful_list = list(set(indexes) - set(temp_list))

然而,我目前使用的代码非常缓慢(因为我有数百万个numpy数组),需要花费数天时间才能运行。是否有更有效的方法在Python中完成相同的操作?


你的缩进有点奇怪。 - Mateen Ulhaq
v[v > 1]怎么样? - Mateen Ulhaq
@MateenUlhaq编辑了问题。 - J Cena
1个回答

4
v = v[v > 1]
indices = np.argpartition(v, -3)[-3:]
values = v[indices]

这里所提到的,argpartition 的时间复杂度为 O(n + k log k)。在你的情况下,n = 1e6k=3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接