Sorting a pandas series

vasek1 picture vasek1 · Aug 26, 2012 · Viewed 9.2k times · Source

I am trying to figure out how to sort the Series generated as a result of a groupby aggregation in a smart way.

I generate an aggregation of my DataFrame like this:

means = df.testColumn.groupby(df.testCategory).mean()

This results in a Series. I now try to sort this by value, but get an error:

means.sort()
...
-> Exception: This Series is a view of some other array, to sort in-place you must create a copy

I then try creating a copy:

meansCopy = Series(means)
meansCopy.sort()
-> Exception: This Series is a view of some other array, to sort in-place you must create a copy

How can I get this sort working?

Answer

Wes McKinney picture Wes McKinney · Aug 26, 2012

Use sort_values, i.e. means = means.sort_values(). [Pandas v0.17+]


(Very old answer, pre-v0.17 / 2015)

pandas used to use order() method: means = means.order().