2016-12-08 55 views
4

鑑於這一數據框:熊貓IndexSlice失敗pd.style

In [1]: df = pd.DataFrame(np.random.rand(4,4), 
          index=['A','B','C','All'], 
          columns=[2011,2012,2013,'All']).round(2) 
     print(df) 
Out[1]: 

    2011 2012 2013 All 
A 0.94 0.17 0.06 0.64 
B 0.49 0.16 0.43 0.64 
C 0.16 0.20 0.22 0.37 
All 0.94 0.04 0.72 0.18 

我試圖使用pd.style格式化數據框的輸出。一個關鍵字是subset,您可以在其中定義應用格式設置規則的位置(例如:突出顯示最大值)。對於pd.style暗示,這是更好地使用pd.IndexSlice這個文檔:

傳遞給subset值表現simlar到切片一個數據幀。

  • 標量被當作一個列標籤
  • 列表(或串聯或numpy的陣列)
  • 元組被視爲(row_indexer,column_indexer)

考慮使用pd.IndexSlice構建最後一個元組的元組。

我想了解爲什麼它在某些情況下失敗。

比方說,我想將一個欄應用於所有行,但第一個和最後一個以及除最後一個以外的所有列。

IndexSlice作品:

In [2]: df.ix[pd.IndexSlice[1:-1,:-1]] 
Out[2]: 
    2011 2012 2013 
B 0.49 0.16 0.43 
C 0.16 0.20 0.22 

但傳遞給style.bar時,它不會:

In [3]: df.style.bar(subset=pd.IndexSlice[1:-1,:-1], color='#d65f5f') 

TypeError: cannot do slice indexing on <class 'pandas.indexes.base.Index'> 
with these indexers [1] of <class 'int'> 

而如果我通過它略有不同,它的工作原理:

In [4]: df.style.bar(subset=pd.IndexSlice[df.index[1:-1],df.columns[:-1]], 
        color='#d65f5f') 

df.style.bar works as expected

我很困惑,爲什麼這不起作用。似乎有點缺乏有關pd.IndexSlice的文檔,所以也許我錯過了一些東西。它也可能是pd.style中的一個錯誤(這是相當新的,因爲只有0.17.1)。

有人可以解釋什麼是錯的?

回答

3

這個兼容性問題太糟糕了。從我可以告訴的是,你回答你自己的問題。從您的文檔的查看您包括行:

元組被視爲(row_indexer,column_indexer)

這不是我們所得到的與第一片:

In [1]: pd.IndexSlice[1:-1,:-1] 
Out[2]: (slice(1, -1, None), slice(None, -1, None)) 

但我們從第二個分片方法中獲得某種形式的東西:

In [3]: pd.IndexSlice[df.index[1:-1],df.columns[:-1]] 
Out[4]: (Index(['B', 'C'], dtype='object'), Index([2011, 2012, 2013], dtype='object')) 

我不' t認爲pd.IndexSlice甚至可以做任何事情,除了在第二種情況下將內容包裝在一個元組中。你可以這樣做:

df.style.bar(subset=(df.index[1:-1],df.columns[:-1]), 
        color='#d65f5f')