vasek1
vasek1

Reputation: 14081

Sorting a pandas series

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?

Upvotes: 29

Views: 11547

Answers (1)

Wes McKinney
Wes McKinney

Reputation: 105591

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().

Upvotes: 34

Related Questions