gpt4 book ai didi

python - 根据另一个 numpy 数组中的值查找 numpy 数组的索引

转载 作者:行者123 更新时间:2023-12-01 21:55:21 26 4
gpt4 key购买 nike

如果索引与另一个较小数组的值匹配,我想在一个较大的数组中找到它们。类似于下面的 new_array:

import numpy as np
summed_rows = np.random.randint(low=1, high=14, size=9999)
common_sums = np.array([7,10,13])
new_array = np.where(summed_rows == common_sums)

但是,这会返回:

__main__:1: DeprecationWarning: elementwise comparison failed; this will raise an error in the future. 
>>>new_array
(array([], dtype=int64),)

我得到的最接近的是:

new_array = [np.array(np.where(summed_rows==important_sum)) for important_sum in common_sums[0]]

这给了我一个包含三个 numpy 数组的列表(每个数组对应一个“重要总和”),但每个数组的长度不同,这会在连接和 vstacking 方面产生进一步的下游问题。明确地说,我不想使用上面的行。我想使用 numpy 索引到 summed_rows。我使用 numpy.wherenumpy.argwherenumpy.intersect1d 查看了各种答案,但无法将这些想法组合在一起.我想我错过了一些简单的东西,问起来会更快。

提前感谢您的建议!

最佳答案

考虑到评论中建议的选项,并使用 numpy 的 in1d 选项添加一个额外的选项:

>>> import numpy as np
>>> summed_rows = np.random.randint(low=1, high=14, size=9999)
>>> common_sums = np.array([7,10,13])
>>> ind_1 = (summed_rows==common_sums[:,None]).any(0).nonzero()[0] # Option of @Brenlla
>>> ind_2 = np.where(summed_rows == common_sums[:, None])[1] # Option of @Ravi Sharma
>>> ind_3 = np.arange(summed_rows.shape[0])[np.in1d(summed_rows, common_sums)]
>>> ind_4 = np.where(np.in1d(summed_rows, common_sums))[0]
>>> ind_5 = np.where(np.isin(summed_rows, common_sums))[0] # Option of @jdehesa

>>> np.array_equal(np.sort(ind_1), np.sort(ind_2))
True
>>> np.array_equal(np.sort(ind_1), np.sort(ind_3))
True
>>> np.array_equal(np.sort(ind_1), np.sort(ind_4))
True
>>> np.array_equal(np.sort(ind_1), np.sort(ind_5))
True

如果你计时,你会发现它们都非常相似,但@Brenlla 的选项是最快的

python -m timeit -s 'import numpy as np; np.random.seed(0); a = np.random.randint(low=1, high=14, size=9999); b = np.array([7,10,13])' 'ind_1 = (a==b[:,None]).any(0).nonzero()[0]'
10000 loops, best of 3: 52.7 usec per loop

python -m timeit -s 'import numpy as np; np.random.seed(0); a = np.random.randint(low=1, high=14, size=9999); b = np.array([7,10,13])' 'ind_2 = np.where(a == b[:, None])[1]'
10000 loops, best of 3: 191 usec per loop

python -m timeit -s 'import numpy as np; np.random.seed(0); a = np.random.randint(low=1, high=14, size=9999); b = np.array([7,10,13])' 'ind_3 = np.arange(a.shape[0])[np.in1d(a, b)]'
10000 loops, best of 3: 103 usec per loop

python -m timeit -s 'import numpy as np; np.random.seed(0); a = np.random.randint(low=1, high=14, size=9999); b = np.array([7,10,13])' 'ind_4 = np.where(np.in1d(a, b))[0]'
10000 loops, best of 3: 63 usec per loo

python -m timeit -s 'import numpy as np; np.random.seed(0); a = np.random.randint(low=1, high=14, size=9999); b = np.array([7,10,13])' 'ind_5 = np.where(np.isin(a, b))[0]'
10000 loops, best of 3: 67.1 usec per loop

关于python - 根据另一个 numpy 数组中的值查找 numpy 数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58066974/

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