【问题标题】:Sorting MultiIndex DataFrame对多索引数据帧进行排序
【发布时间】:2020-07-10 07:01:16
【问题描述】:

我一直在寻找一种方法,按它们包含的值对 MultiIndex DataFrame 中的每个行级别 0、列级别 1 对进行排序,但到目前为止我还没有运气。例如,如果我的 DataFrame 看起来像

import numpy as np
import pandas as pd

np.random.seed(7)
tup = (('A', 'B'), np.arange(2))
index = pd.MultiIndex.from_product(tup, names=('row-lvl 0', 'row-lvl 1'))
tup = (('X', 'Y'), ('q', 'p'))
columns = pd.MultiIndex.from_product(tup, names=('col-lvl 0', 'col-lvl 1'))
data = np.random.rand(4, 4)
df = pd.DataFrame(data, index=index, columns=columns)
print(df)

col-lvl 0                   X                   Y          
col-lvl 1                   q         p         q         p
row-lvl 0 row-lvl 1                                        
A         0          0.076308  0.779919  0.438409  0.723465
          1          0.977990  0.538496  0.501120  0.072051
B         0          0.268439  0.499883  0.679230  0.803739
          1          0.380941  0.065936  0.288146  0.909594

我希望它按升序排列看起来像

col-lvl 0                   X                   Y          
col-lvl 1                   q         p         q         p
row-lvl 0 row-lvl 1                                        
A         0          0.076308  0.538496  0.438409  0.072051
          1          0.977990  0.779919  0.501120  0.723465
B         0          0.268439  0.065936  0.288146  0.803739
          1          0.380941  0.499883  0.679230  0.909594

我已经阅读了有关 sort_values 和 sort_index 的 pandas 文档,但它们似乎不是我想要的。对此的任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas sorting indexing levels


    【解决方案1】:

    这不是 sort_values ,因为您忽略了 index 影响只检查值

    for x , y in df.groupby(level=0):
    ...     df.loc[x]=np.sort(y.values,0)
    ...     
    df
    col-lvl 0                   X                   Y          
    col-lvl 1                   q         p         q         p
    row-lvl 0 row-lvl 1                                        
    A         0          0.076308  0.538496  0.438409  0.072051
              1          0.977990  0.779919  0.501120  0.723465
    B         0          0.268439  0.065936  0.288146  0.803739
              1          0.380941  0.499883  0.679230  0.909594
    

    【讨论】:

    • 感谢您的帮助!这非常有效。请注意,如果 A 或 B 是元组,这将引发错误,因此您可能需要进行一些重新索引。
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2019-10-24
    • 2017-04-27
    • 2023-03-29
    • 2016-01-04
    相关资源
    最近更新 更多