2013-05-24 14 views
5

私は(40,20,30)numpyの配列を持ち、入力した配列の半分を入力軸に沿って返す関数を持っています。それを自動的に行う方法はありますか? 、あなたの助けのためのnumpy配列を任意の次元に沿ってスライスします

def my_function(array,axis=0): 

    ... 

    if axis == 0: 
     return array[:array.shape[0]/2,:,:] --> (20,20,30) array 
    elif axis = 1: 
     return array[:,:array.shape[1]/2,:] --> (40,10,30) array 
    elif axis = 2: 
     return array[:,:,:array.shape[2]/2] --> (40,20,15) array 

おかげ

エリック

答えて

6

私はあなたがこの[docs]ためnp.splitを使用し、単純に返された第一または第二の要素を取ることができると思います。私は、このような醜いコードを避けたいですあなたが望むものに応じて。例:

>>> a = np.random.random((40,20,30)) 
>>> np.split(a, 2, axis=0)[0].shape 
(20, 20, 30) 
>>> np.split(a, 2, axis=1)[0].shape 
(40, 10, 30) 
>>> np.split(a, 2, axis=2)[0].shape 
(40, 20, 15) 
>>> (np.split(a, 2, axis=0)[0] == a[:a.shape[0]/2, :,:]).all() 
True 
+0

FYI:スプリット()は、任意のスプリットポイントを指定するタプルをとります。 – mhsmith

4

ご協力ありがとうございます。私はあなたのアプローチを使用します。一方

、私は(汚れ?)が発見ハック:

>>> a = np.random.random((40,20,30)) 
>>> s = [slice(None),]*a.ndim 
>>> s[axis] = slice(f,l,s) 
>>> a1 = a[s] 

おそらく、もう少し一般的なnp.splitよりははるかに少ないエレガント!

2

numpy.rollaxisは、このための良いツールである:

def my_func(array, axis=0): 
    array = np.rollaxis(array, axis) 
    out = array[:array.shape[0] // 2] 
    # Do stuff with array and out knowing that the axis of interest is now 0 
    ... 

    # If you need to restore the order of the axes 
    if axis == -1: 
     axis = out.shape[0] - 1 
    out = np.rollaxis(out, 0, axis + 1) 
関連する問題