How to create crosstabs from Dictionary in Python

How to create crosstabs from Dictionary in Python

Creating crosstabs, also known as contingency tables or pivot tables, is a common task when working with data in Python. Crosstabs are used to summarize and analyze the relationship between two or more categorical variables. In Python, one way to create crosstabs from a dictionary is by using the pandas library.

The pandas library provides a crosstab() function that can be used to create a crosstab from a dictionary. The crosstab() function takes two arguments: the first argument is the column that will be used for the rows of the crosstab, and the second argument is the column that will be used for the columns of the crosstab. The function returns a new DataFrame containing the crosstab.

Here’s an example of how to create a crosstab from a dictionary using pandas:

import pandas as pd

my_dict = {‘gender’: [‘M’, ‘F’, ‘F’, ‘M’, ‘M’, ‘F’],
‘smoker’: [‘Yes’, ‘No’, ‘No’, ‘No’, ‘Yes’, ‘Yes’]}

df = pd.DataFrame(my_dict)

crosstab = pd.crosstab(df[‘gender’], df[‘smoker’])
print(crosstab)

 

The above code will create a crosstab where gender is on the rows and smoker on the columns, showing the count of observations for each combination.

smoker No Yes
gender
F 1 2
M 1 2

 

It is also possible to normalize the crosstab using the normalize parameter, for example:

crosstab = pd.crosstab(df['gender'], df['smoker'], normalize='columns')

 

This will normalize the data so that the percentages of each cell represent the proportion of that cell with respect to its column.

Crosstabs are a powerful tool for summarizing and analyzing categorical data, and the pandas library makes it easy to create crosstabs from dictionaries in Python. With the pandas.crosstab() method you can easily create crosstabs and get insights from your data.

In this Learn through Codes example, you will learn: How to create crosstabs from Dictionary in Python.



Essential Gigs