ByteBoard Notes Notes

Create a DataFrame from a list of dictionaries

Informatics Practices XII · Experiment 08 of 38 · Pandas

12-IPPandas programs
Expt. No.08
Page No.16

DataFrame from a list of dictionaries

Aim

To write a Python program that creates a DataFrame from a list of dictionaries, one dictionary per row.

Concepts used

Algorithm

  1. Make a list of dictionaries, each holding one student's details (one dictionary has a key missing).
  2. Create the DataFrame with pd.DataFrame() and display it.

Program

# DataFrame from a list of dictionaries import pandas as pd data = [{"Name": "Asha", "Class": "XII", "Marks": 82},        {"Name": "Rohan", "Class": "XII", "Marks": 67},        {"Name": "Ira", "Marks": 88}]df = pd.DataFrame(data)print(df)

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python dataframe_from_list_of_dicts.py
Name Class Marks 0 Asha XII 82 1 Rohan XII 67 2 Ira NaN 88

✓ Printed by running this program, not typed by hand.

Result

Each dictionary became one row and the keys became the columns. Ira's dictionary has no "Class" key, so her Class is NaN.

Viva voce: what the examiner may ask

01In a list of dictionaries, what does each dictionary become?

One row of the DataFrame.

02What is the index of this DataFrame?

The default 0, 1, 2.

03How could the names be used as the index?

Pass index=["S1", "S2", "S3"] when creating it, or create it from different data.

Variations for the lab test

  1. Add a fourth dictionary with a key "City" and see the new column.
  2. Give the DataFrame the index ["S1", "S2", "S3"].
  3. Create the same DataFrame from a dictionary of lists.
! Common mistake Spelling a key differently in one dictionary ("marks" instead of "Marks") creates a separate column with NaN in the other rows.
Back to the 12-IP index