2017-01-25 32 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. ]]])