2017-08-17 89 views

回答

12

df.loc_LocIndexer類的一個實例,它恰好是_NDFrameIndexer類的子類。

當你做df.loc(...),它似乎__call__方法被調用,它無害地返回自己的另一個實例。例如:

In [641]: df.loc 
Out[641]: <pandas.core.indexing._LocIndexer at 0x10eb5f240> 

In [642]: df.loc()()()()()() 
Out[642]: <pandas.core.indexing._LocIndexer at 0x10eb5fe10> 

... 

依此類推。以任何方式不會使用在(...)中傳遞的值。

另一方面,傳遞給[...]的屬性被髮送到檢索/設置的__getitem__/__setitem__

+0

或通過'__setitem__'分配。 OP沒有說明。 –

+0

@MadPhysicist注意,謝謝。 –

+0

通常,可以包含在.loc(...)中的參數是什麼? – user1559897

2

對於任何Python對象,()調用__call__方法,而[]調用__getitem__方法(除非要設置的值,在這種情況下,它調用__setitem__)。換句話說,()[]調用不同的方法,那麼爲什麼你會期望它們的行爲相同呢?

5

作爲其他的答案已經解釋,所述()括號調用__call__方法,其被定義爲:

def __call__(self, axis=None): 
    # we need to return a copy of ourselves 
    new_self = self.__class__(self.obj, self.name) 

    new_self.axis = axis 
    return new_self 

它返回其自身的副本。現在,在()之間傳遞的參數是實例化新副本的axis成員。所以,這可能會提出一個問題,即爲什麼不論你作爲參數傳遞什麼值並不重要,所得到的索引器完全相同。這個問題的答案在於超類_NDFrameIndexer用於多個子類。

對於調用_LocIndexer類的.loc方法,此成員無關緊要。 LocIndexer類本身是_LocationIndexer的一個子類,它是_NDFrameIndexer的子類。

每次被_LocationIndexer調用時,默認爲0,不可能自己指定它。例如,我會參考的類中的功能之一,與其他人紛紛效仿:

def __getitem__(self, key): 
    if type(key) is tuple: 
     key = tuple(com._apply_if_callable(x, self.obj) for x in key) 
     try: 
      if self._is_scalar_access(key): 
       return self._getitem_scalar(key) 
     except (KeyError, IndexError): 
      pass 
     return self._getitem_tuple(key) 
    else: 
     key = com._apply_if_callable(key, self.obj) 
     return self._getitem_axis(key, axis=0) 

所以,無論你在.loc(whatever)傳遞什麼樣的參數,將使用默認值覆蓋。在調用.iloc時會看到類似的行爲,該行爲調用_iLocIndexer(_LocationIndexer),因此默認情況下也會覆蓋axis

這個axis在哪裏呢?答案是:在已棄用的.ix方法中。我有形狀(2187, 5)的數據幀,而現在定義:

a = df.ix(0) 
b= df.ix(1) 
c = df.ix(2) 
a[0] == b[0] #True 
b[0] == c[0] #True 
a[0,1] == b[0,1] #False 

如果你用簡單的標索引,axis仍然忽略了這2-d例如,作爲get方法回落到簡單的基於整型標索引。然而,a[0,1]已形成(2,5) < - 它需要沿着axis=0; b[0,1]已形狀(2187, 2) < - 它需要沿axis=1前兩個條目; c[0,1]返回ValueError: No axis named 2 for object type <class 'pandas.core.frame.DataFrame'>

換句話說:

您仍然可以調用_NDFrameIndexer類的呼叫方法,因爲它是在_IXIndexer子類中使用。但是:從0.20.0開始,.ix索引器已被棄用,以支持更嚴格的.iloc和.loc索引器。將參數傳遞給調用 .iloc和.loc將被忽略。

相關問題