Menu

numpy配列の単純な四則演算+α

2018-10-07 - Numpy

加算

In [3]: np.array([[1,2,3], [4,5,6]]) + np.array([[1,1,1], [2,2,2]])                                                                     
Out[3]: 
array([[2, 3, 4],
       [6, 7, 8]])
In [21]: np.array([[1,2,3], [4,5,6]]) + 2                                                                                               
Out[21]: 
array([[3, 4, 5],
       [6, 7, 8]])

除算

In [5]: np.array([[1,2,3], [4,5,6]]) - np.array([[1,1,1], [2,2,2]])                                                                     
Out[5]: 
array([[0, 1, 2],
       [2, 3, 4]])
In [22]: np.array([[1,2,3], [4,5,6]]) - 2                                                                                               
Out[22]: 
array([[-1,  0,  1],
       [ 2,  3,  4]])

乗算

In [4]: np.array([[1,2,3], [4,5,6]]) * np.array([[1,1,1], [2,2,2]])                                                                     
Out[4]: 
array([[ 1,  2,  3],
       [ 8, 10, 12]])
In [13]: np.array([[1,2,3], [4,5,6]]) * 10                                                                                 
Out[13]: 
array([[10, 20, 30],
       [40, 50, 60]])

割り算

In [6]: np.array([[1,2,3], [4,5,6]]) / np.array([[1,1,1], [2,2,2]])                                                                     
Out[6]: 
array([[1. , 2. , 3. ],
       [2. , 2.5, 3. ]])

余りの計算

In [7]: np.array([[1,2,3], [4,5,6]]) % np.array([[1,1,1], [2,2,2]])                                                                     
Out[7]: 
array([[0, 0, 0],
       [0, 1, 0]])

比較

In [10]: np.array([[1,2,3], [4,5,6]]) < np.array([[1,1,1], [2,10,20]])                                                                  
Out[10]: 
array([[False, False, False],
       [False,  True,  True]])          

○乗の計算

In [16]: np.array([[1,2,3], [4,5,6]]) ** 2                                                                                              
Out[16]: 
array([[ 1,  4,  9],
       [16, 25, 36]])