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?
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.
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.
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.
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.
Use sort_values
, i.e. means = means.sort_values()
. [Pandas v0.17+]
pandas used to use order()
method: means = means.order()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With