2015-09-03 62 views
-1
# *-* coding: utf-8 *-* 

import numpy as np 
import scipy as sc 

A = np.array([[1,1], [1,2], [3,1]]) 
B = np.array([[2,3], [3,2], [1,4]]) 

print (A==B).all() 
print np.array_equal(A, B) 
print np.array_equiv(A, B) 
print np.allclose(A, B) 

但他們只是說「假」,但我仍然可以添加這兩個數組。我必須檢查是否允許添加/乘法(維度?),如果不是,我必須發出錯誤。Python:我如何檢查是否可以添加兩個數組?

+2

...什麼?你想檢查尺寸?當你直接嘗試添加不等尺寸的數組時,numpy會拋出錯誤。 –

+2

你可以試試'[EAFP](https://docs.python.org/3.5/glossary.html#term-eafp)'',你可能不知道它是什麼(還)。 –

回答

4
import numpy as np 

A = np.array([[1, 1], [1, 2], [3, 1]]) 
B = np.array([[2, 3], [3, 2], [1, 4]]) 
C = np.array([[1, 2], [3, 4]]) 

# same shapes --> operations are not a problem 
print(A+B) 
print(A*B) 

# shapes differ --> numpy raises ValueError 
print(A+C) 
print(A*C) 

通過numpy的提出的ValueError異常是類似如下:

ValueError: operands could not be broadcast together with shapes (3,2) (2,2)

正如你所看到的,形狀由numpy做任何陣列操作前檢查。

但是,如果你想這樣做手工或想趕上由numpy引發的異常,你可以做這樣的事情:

# prevent numpy raising an ValueError by prooving array's shapes manually before desired operation 
def multiply(arr1, arr2): 
    if arr1.shape == arr2.shape: 
     return arr1 * arr2 
    else: 
     print('Shapes are not equal. Operation cannot be done.') 

print(multiply(A, B)) 
print(multiply(A, C)) 

# prevent numpy raising an ValueError by prooving array's shapes manually before desired operation 
def add(arr1, arr2): 
    if arr1.shape == arr2.shape: 
     return arr1 + arr2 
    else: 
     print('Shapes are not equal. Operation cannot be done.') 

print(add(A, B)) 
print(add(A, C)) 


# catch the error/exception raised by numpy and handle it like you want to 
try: 
    result = A * C 
except Exception as e: 
    print('Numpy raised an Exception (ValueError) which was caught by try except.') 
else: 
    print(result)  
2

要檢查形狀是否匹配做加法,訣竅將處理廣播,因爲廣播允許添加具有不同形狀的陣列。要檢查這一點,可以使用np.broadcast

下面是一個例子:

a = np.array([[1, 2], [3, 4], [5, 6]]) 
b = np.array([1, 2, 3]) 

a + b # raises value error 
np.broadcast(a, b) # raise value error 

a + b[:,None] # does the addition with broadcasting 
np.broadcast(a, b[:,None]) # returns a valid broadcast object 

如果ab具有相同的形狀,並且可以直接添加,np.broadcast也將返回一個有效的對象而不引發異常。

相關問題