Title: Sorting Rows In pandas Dataframes
Slug: pandas_sorting_rows_dataframe
Summary: Sorting Rows In pandas Dataframes
Date: 2016-05-01 12:00
Category: Python
Tags: Data Wrangling
Authors: Chris Albon

import modules


In [22]:
import pandas as pd

Create dataframe


In [23]:
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 
        'year': [2012, 2012, 2013, 2014, 2014], 
        'reports': [1, 2, 1, 2, 3],
        'coverage': [2, 2, 3, 3, 3]}
df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
df


Out[23]:
coverage name reports year
Cochice 2 Jason 1 2012
Pima 2 Molly 2 2012
Santa Cruz 3 Tina 1 2013
Maricopa 3 Jake 2 2014
Yuma 3 Amy 3 2014

Sort the dataframe's rows by reports, in descending order


In [24]:
df.sort_values(by='reports', ascending=0)


Out[24]:
coverage name reports year
Yuma 3 Amy 3 2014
Pima 2 Molly 2 2012
Maricopa 3 Jake 2 2014
Cochice 2 Jason 1 2012
Santa Cruz 3 Tina 1 2013

Sort the dataframe's rows by coverage and then by reports, in ascending order


In [25]:
df.sort_values(by=['coverage', 'reports'])


Out[25]:
coverage name reports year
Cochice 2 Jason 1 2012
Pima 2 Molly 2 2012
Santa Cruz 3 Tina 1 2013
Maricopa 3 Jake 2 2014
Yuma 3 Amy 3 2014