Recipe: How to rank a Pandas DataFrame?
DATA MUNGING PYTHON PANDAS DATAFRAME PANDAS CHEATSHEET PANDAS DATAFRAME TUTORIAL

How to rank a Pandas DataFrame?

This recipe helps you rank a Pandas DataFrame
In [1]:
## How to rank a Pandas DataFrame
def Kickstarter_Example_100():
    print()
    print(format('How to rank 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': [4, 24, 31, 2, 3],
            'coverage': [25, 94, 57, 62, 70]}

    df = pd.DataFrame(data, index = ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'])
    print(); print(df)

    # Create a new column that is the rank of the value of coverage in ascending order
    df['coverageRanked'] = df['coverage'].rank(ascending=True)
    print(); print(df)

    # Create a new column that is the rank of the value of coverage in descending order
    df['coverageRanked'] = df['coverage'].rank(ascending=False)
    print(); print(df)

Kickstarter_Example_100()
**************************How to rank a Pandas DataFrame**************************

             name  year  reports  coverage
Cochice     Jason  2012        4        25
Pima        Molly  2012       24        94
Santa Cruz   Tina  2013       31        57
Maricopa     Jake  2014        2        62
Yuma          Amy  2014        3        70

             name  year  reports  coverage  coverageRanked
Cochice     Jason  2012        4        25             1.0
Pima        Molly  2012       24        94             5.0
Santa Cruz   Tina  2013       31        57             2.0
Maricopa     Jake  2014        2        62             3.0
Yuma          Amy  2014        3        70             4.0

             name  year  reports  coverage  coverageRanked
Cochice     Jason  2012        4        25             5.0
Pima        Molly  2012       24        94             1.0
Santa Cruz   Tina  2013       31        57             4.0
Maricopa     Jake  2014        2        62             3.0
Yuma          Amy  2014        3        70             2.0


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
5 developers from Tata Consultancy Services
2 developers from Emids
2 developers from Infosys
2 developers from Ericsson
2 developers from HP
2 developers from S&P
1 developer from Altiad
1 developer from Appscook Technologies
1 developer from Bharti Airtel
1 developer from Capital One