How to REINDEX a Pandas Series and DataFrame in Python

January 13, 2019

Contact Seller

Guest Post Description

How to REINDEX a Pandas Series and DataFrame in Python

def Kickstarter_Example_100b(): 
    print()
    print(format('How to reindex Pandas Series and DataFrame','*^82'))    
    import warnings
    warnings.filterwarnings("ignore")
    # load libraries
    import pandas as pd
    # Create a pandas series of the risk of fire in Southern Arizona
    brushFireRisk = pd.Series([34, 23, 12, 23], 
                              index = ['Bisbee', 'Douglas', 
                                       'Sierra Vista', 'Tombstone'])
    print(); print(brushFireRisk)
    # Reindex the series and create a new series variable
    brushFireRiskReindexed = brushFireRisk.reindex(['Tombstone', 'Douglas', 
                             'Bisbee', 'Sierra Vista', 'Barley', 'Tucson'])
    print(); print(brushFireRiskReindexed)
    # Reindex the series and fill in any missing indexes as 0
    brushFireRiskReindexed = brushFireRisk.reindex(['Tombstone', 'Douglas', 
                            'Bisbee', 'Sierra Vista', 'Barley', 'Tucson'], 
                            fill_value = 0)
    print(); print(brushFireRiskReindexed)    
    # Create a dataframe
    data = {'county': ['Cochice', 'Pima', 'Santa Cruz', 'Maricopa', 'Yuma'], 
            'year': [2012, 2012, 2013, 2014, 2014], 
            'reports': [4, 24, 31, 2, 3]}
    df = pd.DataFrame(data)
    print(); print(df)
    # Change the order (the index) of the rows
    print(); print(df.reindex([4, 3, 2, 1, 0]))
    # Change the order (the index) of the columns
    columnsTitles = ['year', 'reports', 'county']
    print(); print(df.reindex(columns=columnsTitles))
Kickstarter_Example_100b()

How to REINDEX a Pandas Series and DataFrame in Python

Add a Review

You must be logged in to post a comment.