Python for Data Science: Chapter 5: NumPy and Pandas Libraries

Pandas: Arithmetic and Data Alignment

Python library

It is possible to perform arithmetic operations using arithmetic operators.

Arithmetic and Data Alignment

• It is possible to perform arithmetic operations using arithmetic operators. Following Python

code illustrates it ‒

 

Python program

import pandas as pd

s1 = pd.Series([10,20,30,40],index=['a', 'b','d', 'e'])

s2 = pd.Series([1,2,3,4],index=['b','c', 'd','f'])

print(s1)

print(s2)

print(s1+s2)

Output


Code explanation: In above code,

1) We have created two series with some indexing.

2) Then using arithmetic operator + we try to add these two series.

3) Note that only common index data gets added.

4) If some index is missing in any of the series, then addition is not possible. It simply displays NaN.

We can pass a fill_value argument with value 0 in the add function so that it will remove NaN values for instance ‒

 

Python program

import pandas as pd

s1 = pd.Series([10,20,30,40],index=['a', 'b', 'd', 'e'])

s2 = pd.Series([1,2,3,4],index=['b','c','d','f'])

print(s1)

print(s2)

print(s1+s2)

print(s1.add(s2,fill_value=0))

Output


Similarly there are methods for other arithmetic operations such as sub, div, mul and pow


Data alignment

When we perform mathematical operations between Panda objects with different indexes, Pandas will perform the data alignment into the resulting Panda object. This operation is known as data alignment.

Following Python code is an illustration of data alignment

 

Python program

import numpy as np

import pandas as pd

df1 = pd.DataFrame(np.arange(9).reshape(3,3), columns=['a','b','c'], index=['Red', 'Blue', 'Green'])

print(df1)

Output

 

Python for Data Science: Chapter 5: NumPy and Pandas Libraries : Tag: Computer Programming, Python, Data Science : Python library - Pandas: Arithmetic and Data Alignment


Python for Data Science: Chapter 5: NumPy and Pandas Libraries



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation