Sorting

January 30, 2018

Sorting

The sort_values function enables us to easily sort data stored in a Series or DataFrame.


Load Libraries

import pandas as pd


Load Data

series = pd.Series([500, 100, 50, 5, 50, 100, 500])


By default, the data is sorted in ascending order. Note that the indexes are unchanged.

series.sort_values()
3      5
2     50
4     50
1    100
5    100
0    500
6    500
dtype: int64


You can pass the parameter ascending=False to sort the series in descending order.

series.sort_values(ascending=False)
6    500
0    500
5    100
1    100
4     50
2     50
3      5
dtype: int64


It is also possible to sort on the index.

series.sort_index()
0    500
1    100
2     50
3      5
4     50
5    100
6    500
dtype: int64


Load Data to DataFrame

sales_data = {'month': ['Jan', 'Feb', 'Jan', 'Feb'], 
              'flavors': ['chocolate', 'vanilla', 'chocolate', 'vanilla'], 
              'cost_price_dollars': [0.50, 0.45, 0.55, 0.50], 
              'number_sold': [100, 150, 200, 125]}

sales = pd.DataFrame(sales_data, columns=['month', 'flavors', 'cost_price_dollars', 'number_sold'])
sales.head()
month flavors cost_price_dollars number_sold
0 Jan chocolate 0.50 100
1 Feb vanilla 0.45 150
2 Jan chocolate 0.55 200
3 Feb vanilla 0.50 125


Sorting the values of a column is easy - simply pass the column to the sort_values function.

sales.sort_values(by=['flavors'])
month flavors cost_price_dollars number_sold
0 Jan chocolate 0.50 100
2 Jan chocolate 0.55 200
1 Feb vanilla 0.45 150
3 Feb vanilla 0.50 125


Sorting multiple columns is very similar.

sales[['month', 'flavors']].sort_values(by=['month', 'flavors'])
month flavors
1 Feb vanilla
3 Feb vanilla
0 Jan chocolate
2 Jan chocolate


When sorting multiple columns, the ascending parameter has an additional function - it lets us specify the order in which each column stated in the by parameter is being sorted.

sales[['month', 'flavors']].sort_values(by=['month', 'flavors'], ascending=[False, True])
month flavors
0 Jan chocolate
2 Jan chocolate
1 Feb vanilla
3 Feb vanilla
comments powered by Disqus