ByteBoard Notes Notes

Create a DataFrame from a dictionary of Series

Informatics Practices XII · Experiment 07 of 38 · Pandas

12-IPPandas programs
Expt. No.07
Page No.14

DataFrame from a dictionary of Series

Aim

To write a Python program that creates a DataFrame from a dictionary of Series and shows how the indexes are aligned.

Concepts used

Algorithm

  1. Create three Series of marks with student names as the index (one Series has a student missing).
  2. Put them in a dictionary: the keys become column names.
  3. Create the DataFrame and display it; the missing value appears as NaN.

Program

# DataFrame from a dictionary of Series import pandas as pd eng = pd.Series([78, 65, 90], index=["Asha", "Bharat", "Chetan"])maths = pd.Series([88, 72, 95], index=["Asha", "Bharat", "Chetan"])ip = pd.Series([91, 84], index=["Asha", "Chetan"]) df = pd.DataFrame({"English": eng, "Maths": maths, "IP": ip})print(df)

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

Output

$ python dataframe_from_dict_of_serie.py
English Maths IP Asha 78 88 91.0 Bharat 65 72 NaN Chetan 90 95 84.0

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

Result

The dictionary keys became the column names and the Series index became the row labels. Bharat has no IP marks in the IP Series, so his IP value is NaN and that column became float64.

Viva voce: what the examiner may ask

01What becomes the column labels?

The keys of the dictionary.

02What becomes the row labels?

The union of all the Series' index labels.

03Why is Bharat's IP mark NaN?

The IP Series has no label "Bharat", so no value was available.

Variations for the lab test

  1. Add a fourth Series for Physics.
  2. Create the DataFrame with the students in a different order.
  3. Make a DataFrame from a dictionary of lists and compare the default index.
! Common mistake Expecting the Series to line up by position: they are aligned by index label, so a missing label gives NaN, not the next value.
Back to the 12-IP index