Sử dụng Pandas, bạn có thể sử dụng isin
:
a1 = np.array([10,5,4,13,10,1,1,22,7,3,15,9])
a2 = np.array([3,4,9,10,13,15,16,18,19,20,21,22,23])
>>> pd.Series(a1).isin(a2).any()
True
Và bằng cách sử dụng chức năng in1d NumPy (theo bình luận từ @Norman):
>>> np.any(np.in1d(a1, a2))
True
Đối với mảng nhỏ như những người trong ví dụ này , giải pháp sử dụng bộ là người chiến thắng rõ ràng. Đối với các mảng lớn hơn, không giống nhau (tức là không có chồng chéo), các giải pháp Pandas và Numpy nhanh hơn. Tuy nhiên, np.intersect1d
xuất hiện để nổi trội hơn cho các mảng lớn hơn.
mảng
nhỏ (12-13 phần)
%timeit set(array1) & set(array2)
The slowest run took 4.22 times longer than the fastest. This could mean that an intermediate result is being cached
1000000 loops, best of 3: 1.69 µs per loop
%timeit any(i in a1 for i in a2)
The slowest run took 12.29 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 1.88 µs per loop
%timeit np.intersect1d(a1, a2)
The slowest run took 10.29 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 15.6 µs per loop
%timeit np.any(np.in1d(a1, a2))
10000 loops, best of 3: 27.1 µs per loop
%timeit pd.Series(a1).isin(a2).any()
10000 loops, best of 3: 135 µs per loop
Sử dụng một mảng với 100k yếu tố (không chồng lên nhau):
a3 = np.random.randint(0, 100000, 100000)
a4 = a3 + 100000
%timeit np.intersect1d(a3, a4)
100 loops, best of 3: 13.8 ms per loop
%timeit pd.Series(a3).isin(a4).any()
100 loops, best of 3: 18.3 ms per loop
%timeit np.any(np.in1d(a3, a4))
100 loops, best of 3: 18.4 ms per loop
%timeit set(a3) & set(a4)
10 loops, best of 3: 23.6 ms per loop
%timeit any(i in a3 for i in a4)
1 loops, best of 3: 34.5 s per loop
Bạn có thể sử dụng 'set' – Nilesh
Sử dụng' np.any (np.in1d (array2, array1)) '. – Norman