Convert Pandas DataFrame to a list of dictionaries

dataframe_to_dicts

Skill - Convert Pandas DataFrame to a list of dictionaries

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Pandas is a python library.
DataFrame is a data structure provided by the pandas library.

Please go through Pandas DataFrame Basics to learn the basics of pandas DataFrame.

In this post, we will learn how to convert pandas dataframe into a list of dictionaries

We might want to convert dataframe to list of objects for scenarios like sending the dataframe content via JSON API, creating rows for database table insertion etc.

The csv file used in this blog post can be downloaded here


Dataframe to list of dictionaries using ‘to_dict’ method

import pandas as pd

# read the csv file into a dataframe named df
df = pd.read_csv('titanic.csv')

# convert the dataframe into list of dictionaries using the .to_dict('records') methos
dfObjects = df.to_dict('records')
print(dfObjects)

Create a dataframe from a list of dictionaries

import pandas as pd

dfObjects = [{'PassengerId': 1, 'Survived': 0, 'Pclass': 3, 'Name': 'Braund, Mr. Owen Harris', 'Sex': 'male'},
{'PassengerId': 2, 'Survived': 1, 'Pclass': 1, 'Name': 'Cumings, Mrs. John Bradley (Florence Briggs Thayer)', 'Sex': 'female'}]

df = pd.DataFrame(data=dfObjects)

Video

Video for this post can be found here


References


Table of Contents

Comments