I'd like to sort data of a multi-index dataframe, while keeping higher level indexes the same.
Here is the data sample:
data = {
'Column 1': [1., 2., 3., 4.,34,2,5,6],
'Index1 Title': [
"Apples", "Apples", "Puppies", "Puppies",
'Oranges','Oranges','Blue berries','Blue berries'],
'index2 Title': [
'Inside', 'Outside', 'Inside', 'Outside',
'Inside', 'Outside', 'Inside', 'Outside'
]
}
df = pd.DataFrame(data)
df.set_index(['Index1 Title','index2 Title'],inplace=True)
I get this output:
Index1 Title index2 Title Column 1
Apples Inside 1.0
Outside 2.0
Puppies Inside 3.0
Outside 4.0
Oranges Inside 34.0
Outside 2.0
Blue berries Inside 5.0
Outside 6.0
When I try this bit of code:
df.sort_values('Column 1', ascending=False)
I get this:
Index1 Title index2 Title Column 1
Oranges Inside 34.0
Blue berries Outside 6.0
Inside 5.0
Puppies Outside 4.0
Inside 3.0
Apples Outside 2.0
Oranges Outside 2.0
Apples Inside 1.0
What I am trying to get, is something resembling what you would get using a pivot table on Excel, as so:
Index1 Title index2 Title Column 1
Oranges Inside 34
Outside 2
Blue berries Inside 5
Outside 6
Puppies Inside 3
Outside 4
Apples Inside 1
Outside 2
Basically making a sum of each Index1 Title values, and sorting them while keeping the Index2 Title structure intact.
I've been struggling with this for a certain time now, couldn't find a fix using standard pandas multi-indexing. Even the reset_index/sort_index routine didn't work
Would a for loop solve it?