Hits: 698
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.
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.