Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

pandas - How sort multiindex dataframe by column value and maintain multiindex structure?

I have a multiindex (TestName and TestResult.Outcome) dataframe, want to sort descending by a column value and maintain the visual multiindex pair (TestName and TestResult.Outcome). How can I achieve that?

For example, I want to sort desc by column "n * %" for TestResult.Outcome index value "Failed" the following table:

enter image description here

I want to achieve the following outcome, maintaining the Pass Fail pairs in the indices: enter image description here

I tried this:

orderedByTotalNxPercentDesc = myDf.sort_values(['TestResult.Outcome','n * %'], ascending=False)

but this orders firstly by index values = "Passed" and breaks the Passed Failed index pairs enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This can help you:

import pandas as pd
import numpy as np

arrays = [np.array(["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"]),np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

df.reset_index().groupby(["level_0"]).apply(lambda x: x.sort_values([3], ascending = False)).set_index(['level_0','level_1'])

In your case 3 is your column n * %, level_0 is your index TestName and level_1 is your TestResult.Outcome.

enter image description here

Becomes:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...