gpt4 book ai didi

python - 将 np.where 应用于方括号过滤以进行 numpy 过滤

转载 作者:太空宇宙 更新时间:2023-11-03 15:36:50 26 4
gpt4 key购买 nike

我可以通过 numpy 数组过滤

a[np.where(a[:,0]==some_expression)]

a[a[:,0]==some_expression]

每个版本的(缺点)优势是什么 - 特别是在性能方面?

最佳答案

bool 索引在内部转换为整数索引。这是 indicated in the docs :

In general if an index includes a Boolean array, the result will be identical to inserting obj.nonzero() into the same position and using the integer array indexing mechanism described above.

所以这两种方法的复杂度是一样的。但是 np.where 对于大型数组更有效:

np.random.seed(0)
a = np.random.randint(0, 10, (10**7, 1))
%timeit a[np.where(a[:, 0] == 5)] # 50.1 ms per loop
%timeit a[a[:, 0] == 5] # 62.6 ms per loop

现在 np.where 还有其他好处:高级整数索引在多个维度上都能很好地工作。有关 bool 索引在这方面不直观的示例,请参见 NumPy indexing: broadcasting with Boolean arrays .由于 np.where 比 bool 索引更有效,这只是它应该被首选的一个额外原因。

关于python - 将 np.where 应用于方括号过滤以进行 numpy 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54309633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com