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 key2
sorter = np.lexsort((key2, key1))
sorted_table = table.take(sorter)
The result would look like this:
In [22]: table
Out[22]:
A B
bar one 0.698202
three 0.801326
two -0.205257
foo one -0.963747
three 0.120621
two 0.189623
Name: C
In [23]: table.take(sorter)
Out[23]:
A B
bar three 0.801326
one 0.698202
two -0.205257
foo two 0.189623
three 0.120621
one -0.963747
Name: 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"