ByteBoard Notes Notes

Create a Series from a scalar value with a custom index

Informatics Practices XII · Experiment 02 of 38 · Pandas

12-IPPandas programs
Expt. No.02
Page No.4

Series from a scalar

Aim

To write a Python program that creates a Series from a scalar value and from a list.

Concepts used

Algorithm

  1. Create a Series from the scalar 5 with an index of three days; the value repeats for every label.
  2. Create a Series from a list with the default index.
  3. Display both.

Program

# Series from a scalar value and from a list import pandas as pd s1 = pd.Series(5, index=["Mon", "Tue", "Wed"])print("Series from a scalar:")print(s1) s2 = pd.Series([3.5, 4.0, 2.5])print("Series from a list (default index):")print(s2)

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

Output

$ python series_from_scalar.py
Series from a scalar: Mon 5 Tue 5 Wed 5 dtype: int64 Series from a list (default index): 0 3.5 1 4.0 2 2.5 dtype: float64

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

Result

The scalar 5 was repeated for each of the three labels Mon, Tue and Wed. The list gave a Series with the default index 0, 1, 2 and dtype float64.

Viva voce: what the examiner may ask

01Why is an index needed when creating a Series from a scalar?

The index tells Pandas how many times to repeat the value and what to label each one.

02What is the dtype of the second Series and why?

float64, because the values have decimals.

03How is a Series different from a list?

A Series has an index (labels) and supports vector operations.

Variations for the lab test

  1. Create a Series of the value 0 for the 12 months.
  2. Create a Series from a list of names.
  3. Create a Series from a scalar string such as "Absent" for five roll numbers.
! Common mistake Writing pd.series(...) with a small s raises AttributeError; the class is Series.
Back to the 12-IP index