2017-01-04 63 views
1

我正在使用一個存儲特定區域氣候數據的numpy數組。該陣列具有以下尺寸:Python:切割一個numpy數組的外框

data.shape[0]=365, data.shape[1]=466 #y,x 

比方說,我想創建由切割出的data外框,例如一個新的數組消除width=5的外框中的值。新的陣列將具有以下尺寸:

new.shape[0]=355, new.shape[1]=456 #y,x 

我目前的陣列形式:

array([[ 0.  , 0.  , 0.  , ..., 0.  , 
      0.  , 0.  ], 
     [ 0.  , 0.  , 0.  , ..., 0.  , 
      0.  , 0.  ], 
     [ 0.  , 0.  , 0.  , ..., 0.  , 
      0.  , 0.  ], 
     ..., 
     [ 17.00830078, 0.  , 0.  , ..., 28.21435547, 
     28.28242111, 28.33056641], 
     [ 0.  , 0.  , 0.  , ..., 28.25419998, 
     28.32392502, 28.34052658], 
     [ 0.  , 0.  , 0.  , ..., 28.23759842, 
     28.31396484, 28.36874962]], dtype=float32) 

這怎麼可能在Python中實現?

+0

你不能只是做'數據[5:data.shape [0] -5,5:data.shape [1 ] -5]'? – EdChum

回答

3

只是slice -

c = 5 # No. of elems to be cropped on either sides 
cropped_out = a[c:-c,c:-c] 

採樣運行 -

In [212]: a 
Out[212]: 
array([[2, 8, 4, 1, 4, 2, 0, 1, 6, 1], 
     [4, 0, 2, 8, 0, 4, 4, 2, 6, 5], 
     [5, 7, 6, 6, 6, 4, 6, 4, 1, 7], 
     [6, 8, 2, 4, 3, 0, 3, 0, 2, 2], 
     [6, 2, 5, 1, 1, 3, 7, 3, 3, 5], 
     [4, 8, 4, 5, 6, 8, 6, 1, 0, 7], 
     [7, 2, 8, 8, 6, 7, 3, 1, 7, 2]]) 

In [213]: c = 2 # No. of elems to be cropped on either sides 

In [214]: a[c:-c,c:-c] 
Out[214]: 
array([[6, 6, 6, 4, 6, 4], 
     [2, 4, 3, 0, 3, 0], 
     [5, 1, 1, 3, 7, 3]]) 
+1

其實這比我上面的評論要乾淨得多,我忘記了負面指數也會在這裏很好地工作+1 – EdChum