[英]Get non sorted column levels in pandas dataframe with multiIndex
背景:
我有一個帶有 MultiIndex 的 Pandas 數據框。
我想讓 column.levels 沒有排序。
df.column.levels 給了我但排序。
例子:
worms=['worm1', 'worm2', 'worm3']
bodyparts=['head', 'vulva', 'tail']
coords=['x', 'y']
arrays=pd.MultiIndex.from_product([worms, bodyparts, coords],
names=['worms', 'bodyparts', 'coords'])
idx = pd.Index(np.arange(0,5000),name='frames')
df=pd.DataFrame(index=idx, columns=arrays)
看起來像這樣:
worms worm1 worm2 worm3
bodyparts head vulva tail head vulva tail head vulva tail
coords x y x y x y x y x y x y x y x y x y
frames
0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
現在,如果我這樣做:
df.columns.levels[1]
我得到:
Index(['head', 'tail', 'vulva'], dtype='object', name='bodyparts')
我想要的是:
Index(['head', 'vulva', 'tail'], dtype='object', name='bodyparts')
有什么選擇嗎?
這為您提供了它們的出現順序:
pd.unique(df.columns.to_frame()['bodyparts'])
輸出: ['head' 'vulva' 'tail']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.