說你有這個多指標-ED數據幀:熊貓:按標籤獲取獨特的多指標水平值
df = pd.DataFrame({'co':['DE','DE','FR','FR'],
'tp':['Lake','Forest','Lake','Forest'],
'area':[10,20,30,40],
'count':[7,5,2,3]})
df = df.set_index(['co','tp'])
,看起來像這樣:
area count
co tp
DE Lake 10 7
Forest 20 5
FR Lake 30 2
Forest 40 3
我想檢索每個唯一值指數級別。這可以通過使用
df.index.levels[0] # returns ['DE', 'FR]
df.index.levels[1] # returns ['Lake', 'Forest']
什麼,我會真的喜歡做的事,是解決各級他們的名字,即'co'
和'tp'
檢索這些列表來完成。我能找到的最短的兩種方式看起來像這樣:
list(set(df.index.get_level_values('co'))) # returns ['DE', 'FR']
df.index.levels[df.index.names.index('co')] # returns ['DE', 'FR']
但它們都非常優雅。有更短的路嗎?
究竟你在這裏找什麼輸出? – acushner