0
0
Pandasdata~5 mins

Arithmetic operations on columns in Pandas

Choose your learning style9 modes available
Introduction

We use arithmetic operations on columns to quickly calculate new values from existing data. This helps us understand and analyze data better.

Calculating total price by multiplying quantity and unit price columns.
Finding the difference between two dates stored in separate columns.
Adding tax to a price column to get the final cost.
Converting units, like changing kilometers to miles in a distance column.
Calculating the average score from multiple test score columns.
Syntax
Pandas
df['new_column'] = df['column1'] + df['column2']
df['new_column'] = df['column1'] - df['column2']
df['new_column'] = df['column1'] * df['column2']
df['new_column'] = df['column1'] / df['column2']

You can use +, -, *, / operators directly on pandas columns.

Make sure columns have numeric data to avoid errors.

Examples
Multiply quantity and price columns to get total cost.
Pandas
df['total'] = df['quantity'] * df['price']
Subtract start time from end time to find duration.
Pandas
df['difference'] = df['end'] - df['start']
Add multiple score columns to get total score.
Pandas
df['sum'] = df['score1'] + df['score2'] + df['score3']
Sample Program

This code creates a table with quantity, price, and discount columns. It calculates total price by multiplying quantity and price. Then it subtracts discount to get the final price.

Pandas
import pandas as pd

data = {
    'quantity': [2, 5, 3],
    'price': [10, 7, 12],
    'discount': [1, 0, 2]
}
df = pd.DataFrame(data)

# Calculate total price without discount
df['total_price'] = df['quantity'] * df['price']

# Calculate final price after discount
df['final_price'] = df['total_price'] - df['discount']

print(df)
OutputSuccess
Important Notes

If columns have missing values, arithmetic operations may result in NaN.

You can chain operations, like (df['a'] + df['b']) * df['c'].

Summary

Arithmetic operations on columns help create new data from existing columns.

Use +, -, *, / operators directly on pandas columns.

Always check data types to avoid errors.