【发布时间】: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