Create a DataFrame from a dictionary of Series
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
- Create three Series of marks with student names as the index (one Series has a student missing).
- Put them in a dictionary: the keys become column names.
- 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
- Add a fourth Series for Physics.
- Create the DataFrame with the students in a different order.
- 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.