philipp-fx
philipp-fx

Reputation: 649

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

Upvotes: 0

Views: 68

Answers (2)

philipp-fx
philipp-fx

Reputation: 649

I was able to get what I want by creating a dummy column for sorting:

iterables = [["bar", "baz", "foo", "qux"], ["one", "two"]]

df = pd.DataFrame(np.random.randn(8, 1), index=arrays)
df.index.names = ['level_0', 'level_1']
df = df.rename(columns={0: "myvalue"}, errors='raise')

for index, row in df.iterrows():
    df.loc[index,'sort_dummy'] = df.loc[(index[0],'two'),'myvalue']

df = df.sort_values(['sort_dummy'], ascending = False)
df

Output:

enter image description here

Upvotes: 0

Jonas Palačionis
Jonas Palačionis

Reputation: 4842

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

Upvotes: 1

Related Questions