假設我有以下 MultiIndex DataFrame,標題為df:
arrays = [["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
["one", "two", "one", "two", "one", "two", "one", "two"],]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=["first", "second"])
df = pd.Series(np.random.randn(8), index=index)
baz例如,如果我想訪問與 關聯的所有行,我將使用 cross-section: df.xs(('baz'))。
但是有沒有辦法通過參考第一級中的整數位置來訪問行,類似于iloc單索引資料幀?在我的示例中,我認為那將是索引位置 1。
我嘗試使用.loc以下解決方法:
(df.loc[[df.index.get_level_values(0)[1]]]
但這會回傳與 關聯的第一組行bar。我相信這是因為整數位置 1 仍在bar. 我必須參考 2 才能到達baz.
我可以讓位置 1、2、3 和 4 分別參考 bar、baz、foo 和 qux 嗎?
uj5u.com熱心網友回復:
您可以使用 levels
df.xs(df.index.levels[0][1])
second
one -1.052578
two 0.565691
dtype: float64
更多細節
df.index.levels[0][0]
'bar'
df.index.levels[0][1]
'baz'
uj5u.com熱心網友回復:
您可以ngroup與groupby和一起使用level=0:
df[(df.groupby(level=0).ngroup() == 1)]
# where 1 is the index of the second group
輸出:
first second
baz one 0.589972
two -0.040558
dtype: float64
在哪里, df.groupby(level=0).ngroup()
回傳:
first second
bar one 0
two 0
baz one 1
two 1
foo one 2
two 2
qux one 3
two 3
dtype: int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357486.html
下一篇:如何在熊貓系列中找到最長的串列?
