Recipe: How to sort rows within a Pandas DataFrame?
DATA MUNGING PYTHON PANDAS DATAFRAME PANDAS CHEATSHEET PANDAS DATAFRAME TUTORIAL

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


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
2 developers from Accenture
2 developers from HCL
1 developer from ANAC
1 developer from Dhruv Technology Solutions
1 developer from FIA Technology Services
1 developer from ICU Medical
1 developer from Network Engg
1 developer from USM Business Systems
1 developer from Beyond Key
1 developer from DXC Technology