2017-05-08 121 views
0

我有一个3D数组,其中包含许多2D数组。我也有一个二维数组。我想从3D数组的每个元素中减去这个二维数组。 我这样做(BT_19是三维阵列,Avg_19是二维数组。A是新的阵列我创建)从3D阵列中减去2D阵列

A=[] 
for i in len(range(BT_19)): 
    ref = BT_19[i]-Avg_19 
    A = np.concatenate((A,[ref]),axis=0) 
    print A 

,然后我得到这个错误,


TypeError         Traceback (most recent call last) 
<ipython-input-83-429b94e5b4d6> in <module>() 
     1 A=[] 
     2 abc=0 
----> 3 for i in len(range(BT_19)): 
     4  ref = BT_19[i]-Avg_19 
     5  A = np.concatenate((A,[ref]),axis=0) 

TypeError: only length-1 arrays can be converted to Python scalars 
+2

'len(range(BT_19))'应该可能是'range(len(BT_19))' - 看起来像一个错误类型。 – yeputons

+0

我没有注意到它。非常感谢 – talullah

回答

0

你可以使用Numpy的广播概念进行计算,因为您有2D矩阵,所以您的操作(减法)将按如下方式向3D矩阵进行广播:

In [1]: x = np.array([[1,1], [2,2]]) 
In [2]: x 
Out[2]: 
array([[1, 1], 
     [2, 2]]) 
In [3]: y = np.random.randint(0,10, size=(5,2,2)) 

In [4]: y.shape 
Out[4]: (5, 2, 2) 

In [5]: y 
Out[5]: 
array([[[3, 2], 
     [4, 6]], 

     [[9, 9], 
     [5, 8]], 

     [[0, 9], 
     [5, 2]], 

     [[6, 3], 
     [9, 5]], 

     [[5, 6], 
     [5, 0]]]) 

In [6]: y - x 
Out[6]: 
array([[[ 2, 1], 
     [ 2, 4]], 

     [[ 8, 8], 
     [ 3, 6]], 

     [[-1, 8], 
     [ 3, 0]], 

     [[ 5, 2], 
     [ 7, 3]], 

     [[ 4, 5], 
     [ 3, -2]]])