How to sort rows within a Pandas DataFrame?
0

How to sort rows within a Pandas DataFrame?

This recipe helps you sort rows within a Pandas DataFrame
In [1]:
## How to sort rows within a Pandas DataFrame
def Snippet_109():
    print()
    print(format('How to sort rows within a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    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'])
    print(); print(df)

    # Sort the dataframe’s rows by reports, in descending order
    print(); print(df.sort_values(by='reports', ascending=0))

    # Sort the dataframe’s rows by reports, in ascending order
    print(); print(df.sort_values(by='reports', ascending=1))

    # Sort the dataframe’s rows by coverage and then by reports, in ascending order
    print(); print(df.sort_values(by=['coverage', 'reports']))

Snippet_109()
********************How to sort rows within a Pandas DataFrame********************

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

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

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

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