2017-01-25 59 views
1

我有形狀爲(600,600,3)的numpy數組,其值爲[-1.0,1.0]。我想將數組擴展爲(600,600,6),其中原始值分成上下0個數。一些示例(1,1,3)數組,其中第n個函數foo()訣竅:Python - 將numpy數組分解爲正分量和負分量

>>> a = [-0.5, 0.2, 0.9] 
>>> foo(a) 
[0.0, 0.5, 0.2, 0.0, 0.9, 0.0] # [positive component, negative component, ...] 
>>> b = [1.0, 0.0, -0.3] # notice the behavior of 0.0 
>>> foo(b) 
[1.0, 0.0, 0.0, 0.0, 0.0, 0.3] 

回答

2

使用切片到最小/最大分配給輸出陣列的不同部分

In [33]: a = np.around(np.random.random((2,2,3))-0.5, 1) 

In [34]: a 
Out[34]: 
array([[[-0.1, 0.3, 0.3], 
     [ 0.3, -0.2, -0.1]], 

     [[-0. , -0.2, 0.3], 
     [-0.1, -0. , 0.1]]]) 

In [35]: out = np.zeros((2,2,6)) 

In [36]: out[:,:,::2] = np.maximum(a, 0) 

In [37]: out[:,:,1::2] = np.maximum(-a, 0) 

In [38]: out 
Out[38]: 
array([[[ 0. , 0.1, 0.3, 0. , 0.3, 0. ], 
     [ 0.3, 0. , 0. , 0.2, 0. , 0.1]], 

     [[-0. , 0. , 0. , 0.2, 0.3, 0. ], 
     [ 0. , 0.1, -0. , 0. , 0.1, 0. ]]])