4  PD: Series & Iteration

import pandas as pd

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
fruits = pd.Series(['apple', 'banana', 'cherry', 'date'])
# 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
custom_indexed_fruits = {f"fruit_{i}": fruit for i, fruit in enumerate(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
numbers = pd.Series([2, 4, 6, 8, 9])
# 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_even = all(num % 2 == 0 for num in numbers)
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
prices = pd.Series([10.5, 8.75, 15.20, 7.5, 9.0])

# Basic list comprehension to create a new list
formatted_prices = [f"${price:.2f}" for price in prices]
print(formatted_prices)

# List comprehension with conditions
expensive_items = [f"${price:.2f}" for price in prices if price > 10]
print(expensive_items)

# Creating a dictionary with list comprehension
price_categories = {f"item_{i}": "expensive" if price > 10 else "budget" 
                    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
codes = pd.Series(['US', 'CA', 'MX', 'BR'])
names = pd.Series(['United States', 'Canada', 'Mexico', 'Brazil'])

# Create a mapping dictionary
country_map = {code: name for code, name in zip(codes, names)}
print(country_map)

# Create a dictionary with more complex transformations
country_info = {code: {'name': name, 'code_length': len(code), 'name_length': len(name)} 
                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
df = pd.DataFrame({
    'product': ['Laptop', 'Phone', 'Tablet', 'Monitor'],
    'price': [1200, 800, 350, 250],
    'stock': [5, 12, 8, 3]
})

# Create a Series of column names and transformation functions
columns_to_transform = pd.Series(['price', 'stock'])
transformations = pd.Series([
    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):
    df[f"{col}_formatted"] = df[col].apply(transform)

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