[英]Pandas MultiIndex Data Frame Sorting
I am looking for a way to sort a multiindex data frame based on one of the indices. 我正在寻找一种基于索引之一对多索引数据帧进行排序的方法。 Here's an example ...
这是一个例子...
I have ... 我有 ...
mi = pd.MultiIndex.from_tuples([('baz', 'y'), ('foo', 'y'), ('bar', 'y'), ('baz', 'z'), ('foo', 'z'), ('bar', 'z')],names=['first','second'])
df = pd.DataFrame(np.random.randn(6),index=mi)
print df
which produces 产生
first second
baz y 1.902902
foo y -0.128341
bar y 0.481100
baz z -2.185144
foo z 1.015320
bar z -1.624616
If I do ... 如果我做 ...
df2 = df.sort()
I get : 我得到:
print df2
first second
bar y 0.481100
z -1.624616
baz y 1.902902
z -2.185144
foo y -0.128341
z 1.015320
How can I sort df such that I get : 如何对df进行排序,使我得到:
first second
baz y 1.902902
z -2.185144
foo y -0.128341
z 1.015320
bar y 0.481100
z -1.624616
I'm not sure how bar is sorted after foo, but I think this is what you want: 我不确定foo后的bar如何排序,但是我认为这是您想要的:
df.sortlevel(0)
0
first second
bar y -0.114659
z 0.453896
baz y -0.327006
z 0.685782
foo y 0.444256
z -0.167179
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.