鑑於這一數據框:熊貓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')
我很困惑,爲什麼這不起作用。似乎有點缺乏有關pd.IndexSlice
的文檔,所以也許我錯過了一些東西。它也可能是pd.style
中的一個錯誤(這是相當新的,因爲只有0.17.1
)。
有人可以解釋什麼是錯的?