ByteBoard Notes Notes

Create a Pandas Series from a dictionary and from an ndarray

Informatics Practices XII · Experiment 01 of 38 · Pandas

★ CBSE suggested12-IPPandas programs
Expt. No.01
Page No.2

Series from a dictionary and an ndarray

Aim

To write a Python program that creates a Pandas Series from a dictionary and from a NumPy ndarray.

Concepts used

Algorithm

  1. Import pandas and numpy.
  2. Create a Series from a dictionary: the keys become the index.
  3. Create an ndarray with np.array() and make a Series from it with a custom index.
  4. Display both Series.

Program

# Series from a dictionary and from an ndarray import pandas as pdimport numpy as np marks = {"English": 78, "Maths": 92, "IP": 88}s1 = pd.Series(marks)print("Series from a dictionary:")print(s1) arr = np.array([10, 20, 30, 40])s2 = pd.Series(arr, index=["a", "b", "c", "d"])print("Series from an ndarray:")print(s2)

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

Output

$ python series_from_dict_ndarray.py
Series from a dictionary: English 78 Maths 92 IP 88 dtype: int64 Series from an ndarray: a 10 b 20 c 30 d 40 dtype: int64

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

Result

The dictionary's keys (English, Maths, IP) became the index of the first Series and its values the data. The second Series took its values from the ndarray and the index a, b, c, d. Both have dtype int64.

Viva voce: what the examiner may ask

01What becomes the index when a Series is made from a dictionary?

The dictionary's keys.

02What is the default index if none is given?

0, 1, 2, … (a RangeIndex).

03What does dtype: int64 at the bottom mean?

The data type of the values: 64-bit integers.

Variations for the lab test

  1. Create a Series from a dictionary of states and capitals.
  2. Create a Series from an ndarray of decimal numbers and check its dtype.
  3. Give the dictionary Series a different order of index labels.
! Common mistake Giving an index list of a different length from the ndarray, e.g. 3 labels for 4 values, raises ValueError.
Back to the 12-IP index