Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 753
vasek1 Avatar asked Aug 26 '12 19:08

vasek1


People also ask

Can you sort a pandas series?

sort_values() function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm.

How do you sort a panda series object?

Sort the Series in Ascending Order By default, the pandas series sort_values() function sorts the series in ascending order. You can also use ascending=True param to explicitly specify to sort in ascending order. Also, if you have any NaN values in the Series, it sort by placing all NaN values at the end.

How do I sort pandas Series index?

Pandas Series: sort_index() functionThe sort_index() function is used to sort Series by index labels. Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None. Axis to direct sorting. This can only be 0 for Series.

How do you sort a series of numbers in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.


1 Answers

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

like image 56
Wes McKinney Avatar answered Oct 01 '22 10:10

Wes McKinney