【发布时间】:2015-08-19 14:11:24
【问题描述】:
我有 2 个数组:x 和 bigx。它们跨越相同的范围,但bigx 有更多的点。
例如
x = np.linspace(0,10,100)
bigx = np.linspace(0,10,1000)
我想在bigx 中找到索引,其中x 和bigx 匹配2 个有效数字。我需要非常快地做到这一点,因为我需要积分的每一步的索引。
使用numpy.where 很慢:
index_bigx = [np.where(np.around(bigx,2) == i) for i in np.around(x,2)]
使用numpy.in1d 的速度提高了约 30 倍
index_bigx = np.where(np.in1d(np.around(bigx), np.around(x,2) == True)
我也尝试使用 zip 和 enumerate,因为我知道这应该更快,但它返回空:
>>> index_bigx = [i for i,(v,myv) in enumerate(zip(np.around(bigx,2), np.around(x,2))) if myv == v]
>>> print index_bigx
[]
我想我一定是把这里的东西弄糊涂了,我想尽可能地优化它。有什么建议?
【问题讨论】:
-
numpy.in1d从您尝试过的列出的可能性中看起来是最优化的方式。 -
是的,但是对于我的目的来说它仍然太慢了。我希望有人可以提出另一种有效的 pythonic 方式来做到这一点。
-
x和bigx是否总是统一的(就像在您的示例中一样)?他们总是排序吗? -
是否期望数组像示例中那样均匀分布?另外,
around(0.0049, 2) != around(0.0051, 2);这些应该被认为是匹配的吗? -
两个数组总是排序的。
bigx总是均匀分布的(而且它是固定的),x不是均匀分布的,它是一个变化的变量 - 因此我希望这种匹配有效,因为我必须多次这样做。
标签: python arrays performance numpy matching