➕ Adding and Modifying Columns
Creating and updating columns is one of the most common data transformation tasks! Whether you're calculating totals, creating categories, or combining existing data, mastering column operations will make you incredibly productive with pandas.
Think of it like adding new information to a spreadsheet - but with the power of programming to handle complex calculations instantly.
import pandas as pd
# Simple product data
products = pd.DataFrame({
'name': ['Laptop', 'Mouse', 'Keyboard'],
'price': [999, 25, 75],
'quantity': [2, 10, 5]
})
print("Original data:")
print(products)
print()
# Add new calculated column
products['total_value'] = products['price'] * products['quantity']
print("With new column:")
print(products)
🎯 Creating New Columns
The simplest way to add a column is using bracket notation:
Mathematical Operations
import pandas as pd
# Sales data
sales = pd.DataFrame({
'item': ['Book', 'Pen', 'Notebook'],
'price': [15.99, 2.50, 8.99],
'quantity': [3, 12, 2]
})
print("Sales data:")
print(sales)
print()
# Add calculated columns
sales['total'] = sales['price'] * sales['quantity']
sales['tax'] = sales['total'] * 0.08
print("With calculations:")
print(sales)
Text Operations
import pandas as pd
# Customer data
customers = pd.DataFrame({
'first_name': ['John', 'Jane', 'Bob'],
'last_name': ['Smith', 'Doe', 'Johnson'],
'city': ['new york', 'chicago', 'boston']
})
print("Customer data:")
print(customers)
print()
# Add text columns
customers['full_name'] = customers['first_name'] + ' ' + customers['last_name']
customers['city_clean'] = customers['city'].str.title()
print("With text operations:")
print(customers[['full_name', 'city_clean']])
🔄 Modifying Existing Columns
Sometimes you need to update existing data rather than create new columns:
Updating Values
import pandas as pd
# Product inventory
inventory = pd.DataFrame({
'product': [' Laptop ', ' mouse ', 'KEYBOARD'],
'price': [999.99, 24.99, 74.99]
})
print("Original inventory:")
print(inventory)
print()
# Clean up the data
inventory['product'] = inventory['product'].str.strip().str.title()
inventory['price'] = inventory['price'].round(0)
print("Cleaned inventory:")
print(inventory)
Conditional Updates
import pandas as pd
# Employee data
employees = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'salary': [45000, 75000, 55000]
})
print("Employee data:")
print(employees)
print()
# Add conditional columns
employees['salary_grade'] = 'Standard'
employees.loc[employees['salary'] > 60000, 'salary_grade'] = 'High'
employees.loc[employees['salary'] < 50000, 'salary_grade'] = 'Entry'
print("With salary grades:")
print(employees)
📊 Advanced Column Operations
Using Multiple Conditions
import pandas as pd
# Student grades
students = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'math': [85, 78, 92],
'english': [90, 85, 89]
})
print("Student grades:")
print(students)
print()
# Calculate average and assign letter grades
students['average'] = (students['math'] + students['english']) / 2
# Assign letter grades
students['letter_grade'] = 'F'
students.loc[students['average'] >= 90, 'letter_grade'] = 'A'
students.loc[students['average'] >= 80, 'letter_grade'] = 'B'
students.loc[students['average'] >= 70, 'letter_grade'] = 'C'
print("With grades:")
print(students)
🔧 Common Column Modifications
📝 Practice: Order Processing
Let's practice with a realistic example:
import pandas as pd
# Customer orders
orders = pd.DataFrame({
'customer': ['Alice', 'Bob', 'Charlie'],
'product': ['laptop', 'mouse', 'keyboard'],
'price': [999, 29, 79],
'quantity': [1, 2, 1],
'discount': [10, 5, 0] # percentage
})
print("Original orders:")
print(orders)
print()
# Calculate totals
orders['subtotal'] = orders['price'] * orders['quantity']
orders['discount_amount'] = orders['subtotal'] * (orders['discount'] / 100)
orders['total'] = orders['subtotal'] - orders['discount_amount']
# Clean product names
orders['product_clean'] = orders['product'].str.title()
print("Processed orders:")
print(orders[['customer', 'product_clean', 'total']])
🎯 Key Takeaways
🚀 What's Next?
Great! You can now create and modify columns like a pro. Next, let's learn how to apply functions to transform your data in more sophisticated ways.
Continue to: Applying Functions
Keep transforming! ➕🔄
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.