亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用一個頂級列對多索引熊貓數據框進行排序?

如何使用一個頂級列對多索引熊貓數據框進行排序?

慕標琳琳 2021-09-24 15:38:32
我有一個這樣的多索引數據集:                                           mean             std                                Happiness Score Happiness ScoreRegion                                                         Australia and New Zealand              7.302500        0.020936Central and Eastern Europe             5.371184        0.578274Eastern Asia                           5.632333        0.502100Latin America and Caribbean            6.069074        0.728157Middle East and Northern Africa        5.387879        1.031656North America                          7.227167        0.179331Southeastern Asia                      5.364077        0.882637Southern Asia                          4.590857        0.535978Sub-Saharan Africa                     4.150957        0.584945Western Europe                         6.693000        0.777886我想按標準偏差對其進行排序。我的嘗試:import numpy as npimport pandas as pddf1.sort_values(by=('Region','std'))如何解決問題?
查看完整描述

3 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

設置


np.random.seed(0)

df = pd.DataFrame(np.random.choice(10, (5, 2)))

df.columns = pd.MultiIndex.from_arrays([['mean', 'std'], ['Happiness Score'] * 2])


df

             mean             std

  Happiness Score Happiness Score

0               5               0

1               3               3

2               7               9

3               3               5

4               2               4

您可以使用argsort和重新索引df:


df.loc[:, ('std', 'Happiness Score')].argsort().values

# array([0, 1, 4, 3, 2])


df.iloc[df.loc[:, ('std', 'Happiness Score')].argsort().values]

# df.iloc[np.argsort(df.loc[:, ('std', 'Happiness Score')])]


             mean             std

  Happiness Score Happiness Score

0               5               0

1               3               3

4               2               4

3               3               5

2               7               9

另一個解決方案是sort_values,傳遞一個元組:


df.sort_values(by=('std', 'Happiness Score'), axis=0)


             mean             std

  Happiness Score Happiness Score

0               5               0

1               3               3

4               2               4

3               3               5

2               7               9

我認為您的想法是正確的,但是元組的順序不正確。


查看完整回答
反對 回復 2021-09-24
  • 3 回答
  • 0 關注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號