[英]Sorting Pandas MultiIndex by the last value of level 0 index
[英]Filling “blank” value in pandas multiindex to access lower level index
我正在使用具有兩級索引的數據框。 第一級用於項目名稱,第二級用於項目顏色。 在第二級索引中,對於所有顏色的總和,我總是有一個名為“ total”的索引名稱。
我想以python返回所有鞋子的“總計”值的方式查詢數據幀。 我可以重新排序索引,但是我正在尋找更清潔的解決方案。 我該怎么辦?
我認為這可能會有所幫助的事情是將索引的“空白”鏈接起來的東西。 這樣的東西可能已經存在了嗎?
例如
df.loc[*blank*,"total",:]
我認為你需要:
與IndexSlice
為選擇的所有值:
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux', 'bar', 'foo']),
np.array(['one','two','one','two','total','two','total', 'two','total','four'])]
df = pd.DataFrame(np.random.randn(10), index=arrays)
print (df)
0
bar one -0.152506
two -0.492401
baz one -1.528111
two -3.284650
foo total -0.346641
two 0.630630
qux total -0.232299
two 0.361744
bar total -2.170350
foo four -2.332996
idx = pd.IndexSlice
df1 = df.loc[idx[:,"total"],:]
print (df1)
0
foo total -0.346641
qux total -0.232299
bar total -2.170350
或使用DataFrame.xs
:
df1 = df.xs('total', level=1)
print (df1)
0
foo -0.099117
qux 0.381831
bar 1.638784
df1 = df.xs('total', level=1, drop_level=False)
print (df1)
0
foo total -0.570454
qux total 0.015090
bar total -1.084960
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.