How to reindex Pandas Series and DataFrames?
0

How to reindex Pandas Series and DataFrames?

This recipe helps you reindex Pandas Series and DataFrames
In [1]:
## How to reindex Pandas Series and DataFrames
def Kickstarter_Example_101():
    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_101()
********************How to reindex Pandas Series and DataFrame********************

Bisbee          34
Douglas         23
Sierra Vista    12
Tombstone       23
dtype: int64

Tombstone       23.0
Douglas         23.0
Bisbee          34.0
Sierra Vista    12.0
Barley           NaN
Tucson           NaN
dtype: float64

Tombstone       23
Douglas         23
Bisbee          34
Sierra Vista    12
Barley           0
Tucson           0
dtype: int64

       county  year  reports
0     Cochice  2012        4
1        Pima  2012       24
2  Santa Cruz  2013       31
3    Maricopa  2014        2
4        Yuma  2014        3

       county  year  reports
4        Yuma  2014        3
3    Maricopa  2014        2
2  Santa Cruz  2013       31
1        Pima  2012       24
0     Cochice  2012        4

   year  reports      county
0  2012        4     Cochice
1  2012       24        Pima
2  2013       31  Santa Cruz
3  2014        2    Maricopa
4  2014        3        Yuma