In this guide, we'll show you how to add a calculated column to a pandas DataFrame in Python. Whether you're a beginner or looking to refresh your skills, these steps will help you perform column operations efficiently.
Step 1: Import pandas and Create a DataFrame
First, import the pandas library and create a sample DataFrame:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3, 4],
'B': [10, 20, 30, 40]
})
Step 2: Add a Simple Calculated Column
To add a column that is the sum of two existing columns, simply assign the result to a new column name:
df['C'] = df['A'] + df['B']
This creates column 'C' with values 11, 22, 33, 44.
Step 3: Using the .assign() Method
For a more functional approach, use .assign():
df = df.assign(D = df['A'] * df['B'])
This adds column 'D' with values 10, 40, 90, 160.
Step 4: Apply Custom Functions
For complex calculations, use .apply() with a lambda function:
df['E'] = df.apply(lambda row: row['A'] ** 2 + row['B'] // 2, axis=1)
Step 5: Add a Column Based on Conditions
Use np.where() for conditional calculations:
import numpy as np
df['F'] = np.where(df['A'] > 2, 'high', 'low')
Conclusion
Adding calculated columns in pandas is straightforward using direct assignment, .assign(), .apply(), or np.where(). These methods are essential for data transformation and analysis in Python.