2013-04-02 57 views
3

我有以下的数组:试图掩盖基于值2D numpy的阵列中的一列

[[ 6.   105.    2.    8.09841881] 
[ 6.   105.    4.    9.34220351] 
[ 6.   105.    6.    9.97663435] 
[ 6.   1001.    2.    9.57108242] 
[ 6.   1001.    4.   12.22355794] 
[ 6.   1001.    6.   13.57295942] 
[ 12.   1001.    2.   12.37474466] 
[ 12.   1001.    4.   17.45334004] 
[ 12.   1001.    6.   19.88499289] 
[ 18.   1007.    2.   16.09076561] 
[ 18.   1007.    4.   23.43742275] 
[ 18.   1007.    6.   27.73041646]] 

我试图仅提取与所述第一元件是一个六经由

print ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==6.0)).T) 

我从问题“mask a 2D numpy array based on values in one column”得到。然而,我得到

File "./Prova.py", line 170, in <module> 
print ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==6.0)).T) 
ValueError: operands could not be broadcast together with shapes (12,4) (12) 

你有线索为什么这不起作用?

这个问题可能是愚蠢的,但请自我承担,因为我刚开始编程python。 :-)

+0

您可能需要在您的掩码中插入一个'np.newaxis'。 – mgilson

+0

这样做会怎样,我该怎么做? –

回答

4

设置一些测试数据上工作:

>>> a = np.arange(12*4).reshape((12,4)) 

首先,我们“分配”空间,为我们遮片阵列:

>>> mask = np.empty(a.shape,dtype=bool) 

现在我们不能分配到它从a == 6第一列直接,因为他们没有适当的形状:

>>> mask[:,:] = a[:,0] == 6 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: operands could not be broadcast together with shapes (12,4) (12) 

但我们可以老兄adcast通过,使之成为一个2-d阵列简单地插入一个newaxis我们的a到正确的形状的第一列:

>>> mask[:,:] = (a[:,0] == 6)[:,np.newaxis] 

正如我们可以看到,我们的掩模现在是正确的。

>>> mask 
array([[ True, True, True, True], 
     [ True, True, True, True], 
     [ True, True, True, True], 
     [ True, True, True, True], 
     [ True, True, True, True], 
     [False, False, False, False], 
     [False, False, False, False], 
     [False, False, False, False], 
     [False, False, False, False], 
     [False, False, False, False], 
     [False, False, False, False], 
     [False, False, False, False]], dtype=bool) 

现在我们只是让我们的蒙面阵列坐下来享受:)。

>>> ma.MaskedArray(a,mask=mask) 
masked_array(data = 
[[-- -- -- --] 
[-- -- -- --] 
[-- -- -- --] 
[-- -- -- --] 
[-- -- -- --] 
[20 21 22 23] 
[24 25 26 27] 
[28 29 30 31] 
[32 33 34 35] 
[36 37 38 39] 
[40 41 42 43] 
[44 45 46 47]], 
      mask = 
[[ True True True True] 
[ True True True True] 
[ True True True True] 
[ True True True True] 
[ True True True True] 
[False False False False] 
[False False False False] 
[False False False False] 
[False False False False] 
[False False False False] 
[False False False False] 
[False False False False]], 
     fill_value = 999999) 
+0

我不相信'.T'会做任何事情,因为第一行是一个1d数组。 – askewchan

+0

它一直不工作。我得到: 文件“./Prova.py”,第171行,在 mask =(np.ones_like(a)*(a [:,0] == 6.0))。T ValueError:操作数无法与形状一起播出(12,4)(12) –

+0

@FerdinandoRandisi - 你说得对。我正在努力... – mgilson