我想逐行比较两个NumPy数组并返回相同行数。
如果我使用以下代码:
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新手。 请帮忙。
I want to compare two NumPy arrays row-wise and return the number of same rows.
If i use the code below:
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)I get the following error:
ValueError: invalid number of argumentsHowever, this works:
np.logical_and([True, False], [False, False])This is probably very silly but I am new to NumPy. Please help.
最满意答案
只是为了扩展@mgilson的答案。 你有正确的想法,首先你做到了这一点:
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( http://docs.scipy.org/doc/numpy/reference/generated/ numpy.logical_and.html )。
因此,如果传入上面的数组,则会得到以下结果:
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值。 这就是回溯告诉你“参数数量无效”的原因。 您需要为此函数提供两个值。
@ zero323正确地给了你一个解决方案,就是将值解包到函数中。 更具体地说,将第一个数组值[True,False]传递给x1,将[False,False]传递给x2:
>>> np.logical_and(*np.equal(a, b)) array([False, False], dtype=bool)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)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 argumentsThis 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 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)更多推荐
发布评论