How to reindex Pandas Series and DataFrames?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to reindex Pandas Series and DataFrames?

How to reindex Pandas Series and DataFrames?

This recipe helps you reindex Pandas Series and DataFrames

5
This python source code does the following: 1.Creates your own data dictionary and converts it into dataframe 2. Imputes the missing values 3. Re-indexes your dataframe
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

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.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

German Credit Dataset Analysis to Classify Loan Applications
In this data science project, you will work with German credit dataset using classification techniques like Decision Tree, Neural Networks etc to classify loan applications using R.

Mercari Price Suggestion Challenge Data Science Project
Data Science Project in Python- Build a machine learning algorithm that automatically suggests the right product prices.

Data Science Project-All State Insurance Claims Severity Prediction
Data science project in R to develop automated methods for predicting the cost and severity of insurance claims.

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.

Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.

Data Science Project-TalkingData AdTracking Fraud Detection
Machine Learning Project in R-Detect fraudulent click traffic for mobile app ads using R data science programming language.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.