简体   繁体   English

如何使用numpy python检查数组

[英]How to check arrays with numpy python

I have two arrays and i want to check how many integers are the same in the different arrays. 我有两个数组,我想检查不同数组中有多少个整数相同。 The problem i'm having is that it only shows me how many are the same when they are in the same position. 我遇到的问题是,当它们处于相同位置时,它仅显示几个相同的对象。 Both arrays have 15 numbers in them. 两个数组中都有15个数字。 Example: 例:

import numpy as np
a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
print(np.count_nonzero(a==b))

This prints 0 even though there's clearly integers that are the same. 即使明显有相同的整数,它也会打印0 How can i make this print how many integers have the same value? 我如何使此打印中有多少个整数具有相同的值?

You want to use np.intersect1d , if I am understanding you correctly: 如果我正确理解您的话,您想使用np.intersect1d

In [12]: import numpy as np

In [13]: a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
    ...: b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
    ...:

In [14]: np.intersect1d(a, b)
Out[14]: array([14, 19, 23])

You can perform broadcasted comparison between b and a , and then just tally up the matches: 您可以在ba之间进行广播比较,然后只需对比赛进行统计:

(b == a[:, None]).sum()
3

This checks out since you have [14, 19, 23] as the common elements. 因为您有[14, 19, 23]作为公共元素[14, 19, 23]所以可以进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM