How to create crosstabs from a Dictionary in Python?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to create crosstabs from a Dictionary in Python?

How to create crosstabs from a Dictionary in Python?

This recipe helps you create crosstabs from a Dictionary in Python

Recipe Objective

Have you ever tried to do a cross features analysis for that you need to create crosstabs basis on different features.

So this is the recipe on we can create crosstabs from a Dictionary in Python.

Step 1 - Import the library

import pandas as pd

We have imported pandas which is needed.

Step 2 - Setting up the Data

We have created a dataset by making a dictionary with features and passing it through the dataframe function. raw_data = {"first_name": ["Sheldon", "Raj", "Leonard", "Howard", "Amy"], "last_name": ["Copper", "Koothrappali", "Hofstadter", "Wolowitz", "Fowler"], "age": [42, 38, 36, 41, 35], "Comedy_Score": [9, 7, 8, 8, 5], "Rating_Score": [25, 25, 49, 62, 70]} df = pd.DataFrame(raw_data, columns = ["first_name", "last_name", "age", "Comedy_Score", "Rating_Score"]) print(df)

Step 3 - Making CrossTab Table

For better understanding we are making different datasets with different number of features for crosstab table. First we have created for one feature that is first_name then in next for two and then for three features. df1 = pd.crosstab(df.first_name, df.age, margins=True) print(df1) df2 = pd.crosstab([df.age, df.Comedy_Score], df.first_name, margins=True) print(df2) df3 = pd.crosstab([df.age, df.Comedy_Score, df.Rating_Score], df.first_name, margins=True) print(df3) So the output comes as

  first_name     last_name  age  Comedy_Score  Rating_Score
0    Sheldon        Copper   42             9            25
1        Raj  Koothrappali   38             7            25
2    Leonard    Hofstadter   36             8            49
3     Howard      Wolowitz   41             8            62
4        Amy        Fowler   35             5            70

age         35  36  38  41  42  All
first_name                         
Amy          1   0   0   0   0    1
Howard       0   0   0   1   0    1
Leonard      0   1   0   0   0    1
Raj          0   0   1   0   0    1
Sheldon      0   0   0   0   1    1
All          1   1   1   1   1    5

first_name        Amy  Howard  Leonard  Raj  Sheldon  All
age Comedy_Score                                         
35  5               1       0        0    0        0    1
36  8               0       0        1    0        0    1
38  7               0       0        0    1        0    1
41  8               0       1        0    0        0    1
42  9               0       0        0    0        1    1
All                 1       1        1    1        1    5

first_name                     Amy  Howard  Leonard  Raj  Sheldon  All
age Comedy_Score Rating_Score                                         
35  5            70              1       0        0    0        0    1
36  8            49              0       0        1    0        0    1
38  7            25              0       0        0    1        0    1
41  8            62              0       1        0    0        0    1
42  9            25              0       0        0    0        1    1
All                              1       1        1    1        1    5

Download Materials

Relevant Projects

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.

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.

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.

Grouping similar schools/colleges using scorecard and other factors
Use cluster analysis to identify the groups of characteristically similar schools in the College Scorecard dataset. Considerations: Clustering Algorithm Data Preparation How will you deal with missing values? Categorical variables? Feature intercorrelations? Feature normalization or scaling? Dimensionality reduction? Hyperparameters How will you set the parameters -- the algorithm's knobs and dials, so to speak -- in order to achieve valid and useful output? Interpretation Is it possible to explain what each cluster represents? Did you retain or prepare a set of features that enables a meaningful interpretation of the clusters? Do the compositions of the clusters seem to make sense? Validation How will you measure the validity of your clustering process? Which metrics will you use and how will you apply them?

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

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.

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

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

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.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.