Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort_values versus sort giving different answers, but sort_values is the correct answer

Tags:

python

pandas

I'm wondering what the difference between these two snippets of code could be?

New_Series = pd.Series(df['avg']).sort(axis=0, ascending=False, 
                                       kind='quicksort', na_position='last', 
                                       inplace=True)
New_Series = pd.Series(df['avg']).sort_values(axis=0, ascending=False, 
                                              kind='quicksort', na_position='last', 
                                              inplace=True)

sort_values returns the correct series, but sort returns None.

Is there a difference between these two that makes sort differently from sort_values?

like image 219
Stephen Juza Avatar asked Nov 27 '16 17:11

Stephen Juza


People also ask

What is the difference between Sort_values and Sort_index method?

The two major sort functions You can check the API for sort_values and sort_index at the Pandas documentation for details on the parameters. sort_values() : You use this to sort the Pandas DataFrame by one or more columns. sort_index() : You use this to sort the Pandas DataFrame by the row index.

How do you sort numbers in a data frame?

To sort the DataFrame based on the values in a single column, you'll use . sort_values() . By default, this will return a new DataFrame sorted in ascending order. It does not modify the original DataFrame.

What is inplace in Sort_values?

The inplace parameter is a more generic term w.r.t pandas and not specific to sort_values alone. You can see it in several functions like pd. fillna, pd. replace etc. Whenever the inplace is set to True, it modifies the existing data frame and you need not assign it to a new data frame.

How do I sort objects in pandas?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.


1 Answers

Apart from the fact that sort is deprecated, it returns None when you use inplace=True

sort_values still returns the self updated dataframe is you use that argument as you can see in frame.py source code:

    if inplace:
        return self._update_inplace(new_data)
    else:
        return self._constructor(new_data).__finalize__(self)
like image 74
Zeugma Avatar answered Oct 04 '22 20:10

Zeugma