ByteBoard Notes Notes

Perform mathematical operations on two Series

Informatics Practices XII · Experiment 03 of 38 · Pandas

12-IPPandas programs
Expt. No.03
Page No.6

Maths on two Series

Aim

To write a Python program that adds, subtracts, multiplies and divides two Series and shows what happens with index labels that do not match.

Concepts used

Algorithm

  1. Create two Series with mostly the same index labels.
  2. Display s1 + s2, s1 − s2, s1 × s2 and s1 ÷ s2.
  3. Labels present in only one Series give NaN.
  4. Multiply a Series by a scalar.

Program

# Mathematical operations on Series import pandas as pd s1 = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])s2 = pd.Series([1, 2, 3, 4], index=["a", "b", "c", "e"]) print("s1 + s2:")print(s1 + s2)print("s1 - s2:")print(s1 - s2)print("s1 * s2:")print(s1 * s2)print("s1 / s2:")print(s1 / s2)print("s1 * 2:")print(s1 * 2)

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

Output

$ python series_math_operations.py
s1 + s2: a 11.0 b 22.0 c 33.0 d NaN e NaN dtype: float64 s1 - s2: a 9.0 b 18.0 c 27.0 d NaN e NaN dtype: float64 s1 * s2: a 10.0 b 40.0 c 90.0 d NaN e NaN dtype: float64 s1 / s2: a 10.0 b 10.0 c 10.0 d NaN e NaN dtype: float64 s1 * 2: a 20 b 40 c 60 d 80 dtype: int64

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

Result

Values with the same label (a, b, c) were combined; d (only in s1) and e (only in s2) gave NaN in every result, which also made the dtype float64. Multiplying by 2 doubled every value of s1.

Viva voce: what the examiner may ask

01How are two Series matched in an operation?

By index label, not by position.

02What is NaN?

"Not a Number": Pandas' marker for a missing value.

03Why did the dtype change to float64?

NaN is a float, so a Series containing NaN is stored as float.

Variations for the lab test

  1. Use s1.add(s2, fill_value=0) to treat missing values as 0. (Not in the syllabus; for curiosity only.)
  2. Find the percentage of s2 in s1.
  3. Add a scalar 5 to every value of s2.
! Common mistake Expecting position-wise results: s1 + s2 lines up the labels, so "d" and "e" do not add up even though they are fourth in each Series.
Back to the 12-IP index