Sorting Rows In pandas Dataframes

Want to learn more? I recommend these Python books: Python for Data Analysis, Python Data Science Handbook, and Introduction to Machine Learning with Python.

import modules

import pandas as pd

Create dataframe

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
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

df.sort_values(by='reports', ascending=0)
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

df.sort_values(by=['coverage', 'reports'])
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