比较两个numpy数组逐行ValueError [英] Compare two numpy arrays row-wise ValueError

查看:100
本文介绍了比较两个numpy数组逐行ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐行比较两个NumPy数组并返回相同行的数量.

I want to compare two NumPy arrays row-wise and return the number of same rows.

如果我使用以下代码:

a=np.array([[1,2],[3,4]])
b=np.array([[1,4],[2,3]])
comp= np.logical_and(np.equal(a,b))
correct=numpy.sum(comp)

我收到以下错误:

ValueError: invalid number of arguments

但是,这可行:

np.logical_and([True, False], [False, False])

这可能很愚蠢,但我是NumPy的新手.请帮忙.

This is probably very silly but I am new to NumPy. Please help.

推荐答案

只是扩展@mgilson的答案.您有正确的主意,首先要做到这一点:

Just to extend the answer from @mgilson. You had the right idea, first you did this:

a = np.array([[1,2],[3,4]])
b = np.array([[1,4],[2,3]])
np.equal(a, b)
>>>array([[ True, False],
   [False, False]], dtype=bool)

现在,您要将其传递给np.logical_and(),如果您查看文档,它将包含两个变量x1和x2(

Now, you want to pass this to np.logical_and(), which if you look at the docs, it takes in two variables, x1 and x2 (http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_and.html).

因此,如果您传递上述数组,则会得到以下内容:

So if you pass in the above array, you get the following:

np.logical_and(np.array([[True, False], [False, False]]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid number of arguments

这是因为np.array([[True,False],[False,True]])是单个数组,即,您只给出了x1值,而没有给出x2值.这就是为什么回溯告诉您无效数量的参数"的原因.您需要为此函数提供两个值.

This is because np.array([[True, False], [False, True]]) is a single array, i.e, you only gave an x1 value, and did not give an x2 value. This is why the traceback tells you 'invalid number of arguments'. You need to give two values to this function.

@ zero323正确地给了您一个解决方案,就是将这些值解压缩到函数中.更具体地说,将第一个数组值[True,False]传递给x1,并将[False,False]传递给x2:

@zero323 rightly gave you one solution, which is to just unpack the values into the function. More specifically, pass the first array value [True, False] into x1, and [False, False] into x2:

>>> np.logical_and(*np.equal(a, b))
array([False, False], dtype=bool)

这篇关于比较两个numpy数组逐行ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆