Skip to main content

Arithmetic Operations

Arithmetic Operations in Pandas

Pandas, a powerful data manipulation library in Python, provides a range of arithmetic operations for numerical data. This article will guide you through these operations, which include addition, subtraction, multiplication, and division. We will also cover other operations like modulus and exponentiation.

Basic Arithmetic Operations

First, let's start with simple arithmetic operations on a Pandas DataFrame.

import pandas as pd

# Creating a simple dataframe
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
})

# Addition
df_add = df + 2
print(df_add)

# Subtraction
df_sub = df - 2
print(df_sub)

# Multiplication
df_mul = df * 2
print(df_mul)

# Division
df_div = df / 2
print(df_div)

In the above examples, each operation is performed on all elements in the DataFrame. This is known as broadcasting.

Element-wise Arithmetic Operations

Pandas also supports element-wise arithmetic operations between two DataFrames.

# Creating two simple dataframes
df1 = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6],
})

df2 = pd.DataFrame({
'A': [7, 8, 9],
'B': [10, 11, 12],
})

# Addition
df_add = df1 + df2
print(df_add)

# Subtraction
df_sub = df1 - df2
print(df_sub)

# Multiplication
df_mul = df1 * df2
print(df_mul)

# Division
df_div = df1 / df2
print(df_div)

Here, each operation is performed on corresponding elements between two dataframes.

Other Arithmetic Operations

Pandas also offers methods for other arithmetic operations.

# Modulus operation
df_mod = df1 % df2
print(df_mod)

# Exponential operation
df_exp = df1 ** df2
print(df_exp)

Dealing with Missing Values in Arithmetic Operations

In real-world data, it's common to encounter missing values. Pandas handles missing values gracefully during arithmetic operations.

# Creating a dataframe with missing values
df_nan = pd.DataFrame({
'A': [1, 2, None],
'B': [4, None, 6],
})

# Addition operation
df_add_nan = df_nan + 2
print(df_add_nan)

In the above example, the arithmetic operation is performed on the existing values, and the missing values are left as they are.

Conclusion

This article covered the basics of arithmetic operations in Pandas, from basic operations to handling missing values. Mastery of these operations is crucial, as they form the backbone of many data manipulation tasks in Python. So keep experimenting and happy data wrangling!