import pandas as pd
4 PD: Series & Iteration
I’ll show you examples of how pandas Series objects work with various Python sequence operations, which demonstrates their seamless integration with Python’s standard library features.
4.1 Using Series with enumerate()
The enumerate()
function pairs each item in an iterable with its index position:
import pandas as pd
# Create a Series
= pd.Series(['apple', 'banana', 'cherry', 'date']) fruits
# Loop on Values
for fruit in fruits:
print(f"{fruit}")
apple
banana
cherry
date
# Loop on Values and Keys
for i, fruit in enumerate(fruits):
print(f"Index {i}: {fruit}")
Index 0: apple
Index 1: banana
Index 2: cherry
Index 3: date
# You can also create a dictionary with custom indices
= {f"fruit_{i}": fruit for i, fruit in enumerate(fruits)}
custom_indexed_fruits print(custom_indexed_fruits)
{'fruit_0': 'apple', 'fruit_1': 'banana', 'fruit_2': 'cherry', 'fruit_3': 'date'}
4.2 Using Series with any()
and all()
These functions check whether any or all elements in an iterable satisfy a condition:
import pandas as pd
# Create a Series of numbers
= pd.Series([2, 4, 6, 8, 9]) numbers
# Check if any number is odd using any()
any(num % 2 == 1 for num in numbers)
True
# Check if all numbers are even using all()
= all(num % 2 == 0 for num in numbers)
all_even all_even
False
# You can also use the built-in Series methods directly
print(f"Any odd numbers (Series method)? {(numbers % 2 == 1).any()}")
print(f"All even numbers (Series method)? {(numbers % 2 == 0).all()}")
Any odd numbers (Series method)? True
All even numbers (Series method)? False
4.3 Using Series with List Comprehensions
List comprehensions work with Series just like with other iterables:
import pandas as pd
# Create a Series
= pd.Series([10.5, 8.75, 15.20, 7.5, 9.0])
prices
# Basic list comprehension to create a new list
= [f"${price:.2f}" for price in prices]
formatted_prices print(formatted_prices)
# List comprehension with conditions
= [f"${price:.2f}" for price in prices if price > 10]
expensive_items print(expensive_items)
# Creating a dictionary with list comprehension
= {f"item_{i}": "expensive" if price > 10 else "budget"
price_categories for i, price in enumerate(prices)}
print(price_categories)
['$10.50', '$8.75', '$15.20', '$7.50', '$9.00']
['$10.50', '$15.20']
{'item_0': 'expensive', 'item_1': 'budget', 'item_2': 'expensive', 'item_3': 'budget', 'item_4': 'budget'}
4.4 Using Series in Dictionary Comprehensions
import pandas as pd
# Create two Series for country codes and names
= pd.Series(['US', 'CA', 'MX', 'BR'])
codes = pd.Series(['United States', 'Canada', 'Mexico', 'Brazil'])
names
# Create a mapping dictionary
= {code: name for code, name in zip(codes, names)}
country_map print(country_map)
# Create a dictionary with more complex transformations
= {code: {'name': name, 'code_length': len(code), 'name_length': len(name)}
country_info for code, name in zip(codes, names)}
print(country_info)
{'US': 'United States', 'CA': 'Canada', 'MX': 'Mexico', 'BR': 'Brazil'}
{'US': {'name': 'United States', 'code_length': 2, 'name_length': 13}, 'CA': {'name': 'Canada', 'code_length': 2, 'name_length': 6}, 'MX': {'name': 'Mexico', 'code_length': 2, 'name_length': 6}, 'BR': {'name': 'Brazil', 'code_length': 2, 'name_length': 6}}
4.5 Practical Application: Dynamic Column Transformations
import pandas as pd
# Create a sample DataFrame
= pd.DataFrame({
df 'product': ['Laptop', 'Phone', 'Tablet', 'Monitor'],
'price': [1200, 800, 350, 250],
'stock': [5, 12, 8, 3]
})
# Create a Series of column names and transformation functions
= pd.Series(['price', 'stock'])
columns_to_transform = pd.Series([
transformations lambda x: f"${x:.2f}", # Format price as currency
lambda x: f"{x} units" # Add 'units' to stock
])
# Apply transformations dynamically
for col, transform in zip(columns_to_transform, transformations):
f"{col}_formatted"] = df[col].apply(transform)
df[
df
product | price | stock | price_formatted | stock_formatted | |
---|---|---|---|---|---|
0 | Laptop | 1200 | 5 | $1200.00 | 5 units |
1 | Phone | 800 | 12 | $800.00 | 12 units |
2 | Tablet | 350 | 8 | $350.00 | 8 units |
3 | Monitor | 250 | 3 | $250.00 | 3 units |