Skip to content Skip to sidebar Skip to footer

Pandas: Sort Pivot Table

Just trying out pandas for the first time, and I am trying to sort a pivot table first by an index, then by the values in a series. So far I've tried: table = pivot_table(sheet1, v

Solution 1:

Here is a solution that may do what you want:

key1 = table.index.labels[0]
key2 = table.rank(ascending=False)

# sort by key1, then key2sorter = np.lexsort((key2, key1))

sorted_table = table.take(sorter)

The result would look like this:

In[22]: tableOut[22]: 
ABbarone0.698202three0.801326two-0.205257fooone-0.963747three0.120621two0.189623Name: CIn[23]: table.take(sorter)
Out[23]: 
ABbarthree0.801326one0.698202two-0.205257footwo0.189623three0.120621one-0.963747Name: C

This would be good to build into pandas as an API method. Not sure what it should look like though.

Post a Comment for "Pandas: Sort Pivot Table"