MODULE 1.1: WORKING WITH PANDAS SERIES - CREATION, VECTORIZATION & OPERATIONS

Explore the foundational building block of Pandas: the 1-dimensional labeled Series. Learn how to construct Series from lists, dictionaries, and NumPy arrays, perform lightning-fast vectorized calculations, and apply custom indexing with 10 real-world examples.

💡 What is a Pandas Series?

A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, Python objects, etc.). While a standard Python list or NumPy array uses integer positions (`0, 1, 2...`) for indexing, a Pandas Series associates every value with a custom label called an **Index**. Think of a Series as a single column of an Excel spreadsheet accompanied by row labels.

1. Creating a Series from a Standard Python List
The simplest way to create a Series is by passing a Python list of values. Pandas automatically generates default integer indices (`0, 1, 2...`).
Python (series_from_list.py)
import pandas as pd

def create_series_list():
    temperatures = [32.5, 34.0, 31.2, 35.8, 33.1]
    
    # Convert list to Pandas Series
    temp_series = pd.Series(temperatures)
    
    print("--- Temperature Series ---")
    print(temp_series)

create_series_list()
Output: --- Temperature Series --- 0 32.5 1 34.0 2 31.2 3 35.8 4 33.1 dtype: float64
2. Creating a Series with Custom String Indices
Assigning custom labels (index) to data points, such as mapping daily stock prices to specific days of the week.
Python (custom_index_series.py)
import pandas as pd

def create_custom_indexed_series():
    prices = [150.25, 152.00, 149.80, 154.50, 156.10]
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
    
    stock_series = pd.Series(prices, index=days)
    
    print("--- Stock Price Series ---")
    print(stock_series)

create_custom_indexed_series()
Output: --- Stock Price Series --- Monday 150.25 Tuesday 152.00 Wednesday 149.80 Thursday 154.50 Friday 156.10 dtype: float64
3. Creating a Series from a Python Dictionary
When keys naturally map to values (e.g., city populations), passing a dictionary automatically assigns dictionary keys as indices.
Python (series_from_dict.py)
import pandas as pd

def create_from_dict():
    city_population = {
        'Mumbai': 20960000,
        'Delhi': 32900000,
        'Bangalore': 13190000,
        'Pune': 7200000
    }
    
    pop_series = pd.Series(city_population)
    print("--- City Population Series ---")
    print(pop_series)

create_from_dict()
Output: --- City Population Series --- Mumbai 20960000 Delhi 32900000 Bangalore 13190000 Pune 7200000 dtype: int64
4. Vectorized Arithmetic Operations on Series
Pandas Series support lightning-fast vectorized math without requiring explicit `for` loops. Here we apply a 10% tax increase across all item prices simultaneously.
Python (vectorized_math.py)
import pandas as pd

def apply_vectorized_math():
    base_prices = pd.Series([100.0, 250.0, 50.0, 500.0], index=['Shirt', 'Jeans', 'Cap', 'Jacket'])
    
    # Vectorized scalar addition & multiplication
    taxed_prices = base_prices * 1.08  # 8% tax
    
    print("--- Original Prices ---")
    print(base_prices)
    print("\n--- Prices After 8% Tax ---")
    print(taxed_prices)

apply_vectorized_math()
Output: --- Original Prices --- Shirt 100.0 Jeans 250.0 Cap 50.0 Jacket 500.0 dtype: float64 --- Prices After 8% Tax --- Shirt 108.0 Jeans 270.0 Cap 54.0 Jacket 540.0 dtype: float64
5. Element Alignment & Addition Between Two Series
When adding two Series, Pandas automatically aligns data based on their index labels, matching corresponding elements even if they are in different orders.
Python (series_alignment.py)
import pandas as pd

def align_series():
    q1_sales = pd.Series([120, 95, 150], index=['Apple', 'Samsung', 'OnePlus'])
    q2_sales = pd.Series([140, 110, 130], index=['Samsung', 'Apple', 'OnePlus'])
    
    total_sales = q1_sales + q2_sales
    print("--- Q1 + Q2 Sales (Index Aligned) ---")
    print(total_sales)

align_series()
Output: --- Q1 + Q2 Sales (Index Aligned) --- Apple 230 OnePlus 280 Samsung 235 dtype: int64
6. Filtering and Boolean Masking on Series
Extracting specific elements from a Series using conditional boolean criteria (e.g., finding products priced above $100).
Python (series_filtering.py)
import pandas as pd

def filter_series():
    gadgets = pd.Series([45, 120, 80, 350, 95], index=['Mouse', 'Headphones', 'Keyboard', 'Tablet', 'Webcam'])
    
    # Filter gadgets costing more than $90
    expensive = gadgets[gadgets > 90]
    
    print("--- Gadgets Costing > $90 ---")
    print(expensive)

filter_series()
Output: --- Gadgets Costing > $90 --- Headphones 120 Tablet 350 Webcam 95 dtype: int64
7. Handling Missing Values (`NaN`) in Series
Detecting, filling, or dropping missing data points (`NaN`) within a sensor or survey telemetry Series.
Python (series_missing.py)
import pandas as pd
import numpy as np

def handle_missing_series():
    ratings = pd.Series([4.5, np.nan, 3.8, 5.0, np.nan], index=['User1', 'User2', 'User3', 'User4', 'User5'])
    
    print("--- Original with NaNs ---")
    print(ratings)
    
    # Fill missing ratings with the mean rating
    filled_ratings = ratings.fillna(ratings.mean())
    print("\n--- Imputed Ratings ---")
    print(filled_ratings)

handle_missing_series()
Output: --- Original with NaNs --- User1 4.5 User2 NaN User3 3.8 User4 5.0 User5 NaN dtype: float64 --- Imputed Ratings --- User1 4.500000 User2 4.433333 User3 3.800000 User4 5.000000 User5 4.433333 dtype: float64
8. Statistical Aggregations on Series
Computing core mathematical and statistical aggregates (mean, median, standard deviation, sum) on numeric Series data.
Python (series_stats.py)
import pandas as pd

def compute_stats():
    monthly_expenses = pd.Series([1200, 450, 300, 1500, 200, 80], index=['Rent', 'Groceries', 'Utilities', 'EMI', 'Transport', 'Entertainment'])
    
    print(f"Total Expenses: ${monthly_expenses.sum()}")
    print(f"Average Expense: ${monthly_expenses.mean():.2f}")
    print(f"Highest Expense: ${monthly_expenses.max()} ({monthly_expenses.idxmax()})")
    print(f"Lowest Expense: ${monthly_expenses.min()} ({monthly_expenses.idxmin()})")

compute_stats()
Output: Total Expenses: $3430 Average Expense: $571.67 Highest Expense: $1500 (EMI) Lowest Expense: $80 (Entertainment)
9. String Manipulation Methods on String Series (`.str`)
Using Pandas built-in `.str` accessor to clean, uppercase, slice, or replace string data across an entire Series efficiently.
Python (series_string_ops.py)
import pandas as pd

def manipulate_strings():
    names = pd.Series(['  alice smith ', 'bob JONES', '  charlie brown'])
    
    # Clean whitespace, capitalize properly
    cleaned_names = names.str.strip().str.title()
    
    print("--- Cleaned Names Series ---")
    print(cleaned_names)

manipulate_strings()
Output: --- Cleaned Names Series --- 0 Alice Smith 1 Bob Jones 2 Charlie Brown dtype: object
10. Converting a Series to NumPy Arrays and Dictionaries
Extracting underlying raw data arrays or converting Series back to standard Python dictionaries for downstream APIs or machine learning models.
Python (series_conversion.py)
import pandas as pd

def convert_series():
    scores = pd.Series([88, 95, 79], index=['Math', 'Science', 'English'])
    
    # Convert to NumPy array
    np_array = scores.to_numpy()
    
    # Convert to Python dictionary
    py_dict = scores.to_dict()
    
    print("NumPy Array:", np_array)
    print("Python Dict:", py_dict)

convert_series()
Output: NumPy Array: [88 95 79] Python Dict: {'Math': 88, 'Science': 95, 'English': 79}