2011-10-07 63 views
0

我在使numpy.any()在我的問題上正常工作時遇到了一些小問題。 考慮我有一個N×M×M矩陣的3D矩陣,我需要擺脫任何具有所有元素相同的[所有零說]的矩陣MXM。 下面是一個例子來說明我的問題需要對numpy.any進行小小的說明,對於矩陣

x = np.arange(250).reshape(10,5,5) 
x[0,:,:] = 0 

我需要做的就是擺脫第一5x5矩陣,因爲它包含所有零是什麼。 所以我試着用

np.any(x,axis=0) 

,並預計將有

[FALSE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE] 

一個結果,但我得到的是

array([[ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True] 
    [ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True], 
    [ True, True, True, True, True]], dtype=bool) 

運用follwing結果與我想要什麼,但我希望,沒有任何迴路有更好的方法

for i in range(x.shape[0]): 
     y.append(np.any(x[i,:,:])) 

我在這裏的某處犯了錯嗎? 謝謝!

+1

看起來我正在用文字去挑選,但是你*不能*有一個比(或更少)2維的矩陣。你的問題作爲一個關於數組的問題是有效的(它可以有任意的維數)。我寫了一篇關於這個的博客文章:http://wilsonericn.wordpress.com/2011/09/15/the-first-thing-you-should -know-大約矩陣/ –

回答

3

x[0,:,:] = 0一個10x5x5矩陣我期望的結果:

[False, True, True, True, True, True, True, True, True, True] 

,因爲它是第一個 5x5的陣列,這是所有零的不和。

你得到使用

x.any(axis=1).any(axis=1) 

x.any(axis=2).any(axis=1) 

這個結果,這意味着你先消除所述第二(軸線= 1)或第三(ASIX = 2)尺寸,然後將剩餘的第二(axis = 1),並且您將獲得唯一的一個維度,它最初是第一個維度(axis = 0)。