How to reindex Pandas Series and DataFrames?
5

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

Relevant Projects

Big Data Project Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.
Big Data Project Sequence Classification with LSTM RNN in Python with Keras
In this project, we are going to work on Sequence to Sequence Prediction using IMDB Movie Review Dataset​ using Keras in Python.
Big Data Project Anomaly Detection Using Deep Learning and Autoencoders
Deep Learning Project- Learn about implementation of a machine learning algorithm using autoencoders for anomaly detection.
Big Data Project Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.
Big Data Project Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.
Big Data Project PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.
Big Data Project Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.
Big Data Project Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.
Big Data Project Learn to prepare data for your next machine learning project
Text data requires special preparation before you can start using it for any machine learning project.In this ML project, you will learn about applying Machine Learning models to create classifiers and learn how to make sense of textual data.
Big Data Project Data Science Project - Instacart Market Basket Analysis
Data Science Project - Build a recommendation engine which will predict the products to be purchased by an Instacart consumer again.