2017-06-22 84 views
1

我想寫一個對象,它允許索引numpy數組的第一個維度,並應防止任何其他索引。索引在Numpy中的特定維度,並防止索引任何其他

import numpy as np 

class Foo: 
    """ 
    Object that allows indexing the first dimension of arr 
    """ 
    def __getitem__(self, my_slice): 
     arr = np.arange(12).reshape((3, 4)) 
     return arr[my_slice] 

foo = Foo() 

# Valid usages: 
foo[0] # first row of arr 
foo[:2] # two first rows of arr 
foo[[0, 2]] # rows 0 and 2 of arr 

# Invalid usages that must raise an Exception but are currently not: 
foo[0, 0] 
foo[..., 0] 
foo[np.newaxis] 
foo[[0,2], [0]] 
foo[[[0,2], [0]]] 
foo[[0,2, np.newaxis]] 

根據以上(arr[my_slide])的解決方案,有效的情況下,通過(好),但無效的情況下,通得過(不好)。 __getitem__爲了滿足所有要求要投入什麼?

+0

「我正在嘗試編寫一個對象,該對象允許索引numpy數組的第一個維度,並且應該防止任何其他索引。」 - 你爲什麼想這樣做?你關心他們是否做了像'foo [:] [:,0]'? – user2357112

+0

我關心,因爲我實際上索引幾個數組。所有這些數組的第一維具有相同的含義,因此索引它們是有意義的,但其他維度具有不同的含義。索引這些其他維度會產生可怕的錯誤。 –

回答

0

可能最簡單的方法就是將my_slice包裝在tuple中。考慮到這是應該理解爲指數的第一維數組的第一個(也是唯一一個)元素:

import numpy as np 

class Foo: 
    def __getitem__(self, my_slice): 
     arr = np.arange(12).reshape((3, 4)) 
     return arr[tuple([my_slice])] # or "return arr[my_slice, ]" 
+0

謝謝!它最初的問題很好。但是我發現了更多令人討厭的情況(用列表索引);比照我更新的問題。任何建議? –

+0

@NicolasBedou我更新了答案。 'foo [0,0]'的情況仍然有效,但與往常不同(它只是將第一維索引兩次):) – MSeifert

+0

謝謝,但是在我看來''foo [0,0]''不是可以接受但太令人驚訝。 –

0

這裏是一個更好的解決方案是,一個在原崗位:

class Foo: 
    """ 
    Object that allows indexing the first dimension of arr 
    """ 
    def __getitem__(self, my_slice): 
     arr = np.arange(12).reshape((3, 4)) 

     if np.empty(arr.shape[0])[my_slice].ndim > 1: 
      raise IndexError 
     return arr[my_slice] 

在此情況下,foo[0, 0]foo[np.newaxis]會根據需要增加IndexError,但某些情況(如foo[..., 0])未正確處理。 所以問題仍然存在。