gpt4 book ai didi

python - 如何获取属于所有 numpy 数组的项目?

转载 作者:太空宇宙 更新时间:2023-11-04 09:08:33 26 4
gpt4 key购买 nike

我需要一些类似于 numpy.in1d() 函数的东西,我的任务是拥有超过 2 个数组的项目列表。例如我有 3 个数组:

a = np.array((1,2,5,6,12))
b = np.array((1,3,7,8,5,14,19))
c = np.array((2,6,9,5,1,22))

结果应该是[1, 5]

有没有比使用 np.in1d 的纯循环更快的方法首先与所有其他方法进行比较?一些数组联合或一些智能子索引?

最佳答案

您可以使用 np.intersect1d。例如:

In [15]: np.intersect1d(a, np.intersect1d(b, c))
Out[15]: array([1, 5])

或使用reduce:

In [16]: reduce(np.intersect1d, (a, b, c))
Out[16]: array([1, 5])

如果您知道每个数组中的元素都是唯一的,请使用参数 assume_unique=True:

In [21]: reduce(lambda x, y: np.intersect1d(x, y, assume_unique=True), (a, b, c))
Out[21]: array([1, 5])

关于python - 如何获取属于所有 numpy 数组的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766145/

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