# Module 8: Data Manipulation ## Learning Objectives By the end of this module, you will be able to: - Select data precisely with `.loc[]` and `.iloc[]` - Filter data using `.query()` and boolean indexing - Apply functions to data with `.apply()`, `.map()`, and `.applymap()` - Use lambda functions for inline transformations - Replace values conditionally --- ## `.loc[]` — Label-Based Selection `.loc[]` selects data by row and column **labels**. The end label is **inclusive**. ```python import pandas as pd df = pd.DataFrame({ "Name": ["Alice", "Bob", "Charlie", "Diana"], "Age": [25, 30, 35, 28], "Salary": [50000, 60000, 70000, 55000], "Department": ["HR", "IT", "IT", "HR"], }, index=["A", "B", "C", "D"]) print(df) ``` ### Row selection ```python # Single row print(df.loc["A"]) # Multiple rows (inclusive) print(df.loc["A":"C"]) # List of labels print(df.loc[["A", "C", "D"]]) ``` ### Row and column selection ```python # Specific row and column print(df.loc["B", "Salary"]) # Specific rows and specific columns print(df.loc["A":"C", ["Name", "Age"]]) # All rows, specific columns print(df.loc[:, ["Name", "Salary"]]) ``` ### Boolean conditions with `.loc[]` ```python # All rows where Age > 28, only Name and Age columns print(df.loc[df["Age"] > 28, ["Name", "Age"]]) # Complex condition print(df.loc[(df["Age"] > 25) & (df["Department"] == "IT"), ["Name", "Salary"]]) ``` ```{tip} Use `.loc[]` whenever you know column names. It makes your code self-documenting and avoids brittle positional indexing. ``` ## `.iloc[]` — Position-Based Selection `.iloc[]` selects data by integer **position**. The end position is **exclusive** (standard Python slicing). ```python # Single row print(df.iloc[0]) # Multiple rows (exclusive of 3) print(df.iloc[0:3]) # Specific row and column print(df.iloc[1, 2]) # Row 1, column 2 → 60000 # Specific rows and columns print(df.iloc[[0, 2], [0, 2]]) # All rows, first two columns print(df.iloc[:, :2]) ``` ### `.loc[]` vs `.iloc[]` comparison | Operation | `.loc[]` | `.iloc[]` | |-----------|----------|-----------| | Selection basis | Labels | Integer positions | | Slice end | Inclusive | Exclusive | | Example | `df.loc["A":"C"]` | `df.iloc[0:3]` | | Best for | Meaningful indexes | Numeric-only indexes | ```{warning} Mixing `.loc[]` and `.iloc[]` with a `RangeIndex` (0, 1, 2, ...) can be confusing. When using the default index, `.iloc[]` is safer because its behaviour is unambiguous. ``` ## `.query()` — String-Based Filtering `.query()` allows you to filter rows using a string expression. This is often cleaner than chained boolean conditions. ```python # Simple condition print(df.query("Age > 28")) # Multiple conditions (use `and` / `or` / `not`) print(df.query("Age > 25 and Department == 'IT'")) # Using variables with @ min_age = 25 max_salary = 65000 print(df.query("Age >= @min_age and Salary <= @max_salary")) # Inline computations print(df.query("Salary / Age > 1500")) ``` ```{note} `.query()` uses `@` to reference Python variables. It is slightly faster than boolean indexing for large DataFrames because it avoids creating intermediate boolean arrays. ``` ### When to use `.query()` vs boolean indexing ```python # Boolean indexing — good for simple conditions df[df["Age"] > 30] # Boolean indexing — complex conditions need parentheses df[(df["Age"] > 25) & (df["Department"] == "IT")] # .query() — cleaner for complex conditions df.query("Age > 25 and Department == 'IT'") ``` ## Boolean Indexing Boolean indexing is the most direct way to filter DataFrames using Python logical operators. ```python # Create a boolean mask mask = df["Age"] > 28 # Apply mask print(df[mask]) # Comparison operators print(df[df["Age"] != 30]) print(df[df["Salary"] >= 60000]) # String methods print(df[df["Name"].str.startswith("A")]) print(df[df["Department"].str.contains("H|I", regex=True)]) # Multiple conditions (parentheses required) print(df[(df["Age"] > 25) | (df["Department"] == "HR")]) print(df[~(df["Department"] == "IT")]) # NOT condition # isin for multiple value matching print(df[df["Department"].isin(["HR", "Sales"])]) ``` ```{tip} Always wrap each condition in parentheses when combining with `&`, `|`, or `~` due to Python operator precedence. ``` ## `.apply()` — Apply Function to Axis `.apply()` applies a function along a DataFrame axis (rows or columns). ### Apply to columns ```python # Apply a NumPy function to each column print(df[["Age", "Salary"]].apply(np.sum)) # Apply a custom function to each column def range_stat(series): return series.max() - series.min() print(df[["Age", "Salary"]].apply(range_stat)) ``` ### Apply to rows (axis=1) ```python # Calculate a new column from multiple columns def categorize_salary(row): if row["Salary"] > 65000: return "High" elif row["Salary"] > 55000: return "Medium" else: return "Low" df["Salary_Tier"] = df.apply(categorize_salary, axis=1) # More concise with lambda df["Bonus"] = df.apply( lambda row: row["Salary"] * 0.1 if row["Department"] == "IT" else row["Salary"] * 0.05, axis=1, ) ``` ```{note} `.apply()` with `axis=1` iterates over rows and can be slow for large DataFrames. For vectorised operations, prefer native Pandas methods or `.apply()` with `axis=0` (the default). ``` ### Using `result_type` ```python # Expand a function result into multiple columns def split_name(name): parts = name.split() return pd.Series([parts[0], parts[1]]) df[["First", "Last"]] = df["Name"].apply(split_name) ``` ## `.map()` — Transform Series Values `.map()` is used for element-wise transformation of a Series. ### With a dictionary ```python # Map gender codes df["Dept_Abbr"] = df["Department"].map({"HR": "Human Resources", "IT": "Information Technology"}) # Map to binary flags df["Is_IT"] = df["Department"].map({"IT": 1, "HR": 0}) ``` ### With a function ```python # Apply a function to every element df["Name_Upper"] = df["Name"].map(str.upper) # Custom transformation df["Salary_K"] = df["Salary"].map(lambda x: round(x / 1000, 1)) ``` ```{warning} `.map()` only works on Series. NaNs in the input will remain NaN unless explicitly handled in the mapping dictionary. ``` ### `.map()` vs `.apply()` | Method | Works on | Purpose | |--------|----------|---------| | `.map()` | Series | Element-wise transformation (dict or function) | | `.apply()` | Series or DataFrame | Apply function to each element, column, or row | ## `.replace()` — Value Replacement `.replace()` is a flexible method for substituting values. ```python # Simple replacement df["Department"] = df["Department"].replace("HR", "Human Resources") # Multiple replacements with a dict df["Department"] = df["Department"].replace({ "HR": "Human Resources", "IT": "Information Technology", }) # Replace in multiple columns df = df.replace({"?": None, "N/A": None, "": None}) # Regex replacement df["Name"] = df["Name"].replace(r"(?i)^a", "A-", regex=True) ``` ```{tip} Use `.replace()` with a dictionary when you have a fixed mapping. For more complex logic, use `.apply()` or `.map()` with a function. ``` ## Lambda Functions Lambda functions (anonymous, single-expression functions) are used extensively with `.apply()`, `.map()`, and `.applymap()`. ```python # Inline transformation df["Age_Double"] = df["Age"].apply(lambda x: x * 2) # Conditional logic df["Age_Group"] = df["Age"].apply( lambda x: "Young" if x < 30 else "Mid" if x < 40 else "Senior" ) # Multiple column operation df["Age_Salary_Ratio"] = df.apply( lambda row: row["Salary"] / row["Age"] if row["Age"] > 0 else 0, axis=1, ) # With .map() df["Name_Initials"] = df["Name"].map(lambda x: "".join([w[0] for w in x.split()])) # Sorting with lambda df_sorted = df.sort_values( by="Name", key=lambda col: col.str.lower(), ) ``` ```{note} Lambda functions are powerful but should be kept simple. If the logic exceeds a single expression, define a named function instead for readability. ``` ## Advanced `.apply()` Examples ```python # Apply with additional arguments def scale(series, factor=1): return series * factor df["Salary_Scaled"] = df["Salary"].apply(scale, args=(1.05,)) # Apply with keyword arguments df["Salary_Scaled"] = df["Salary"].apply(scale, factor=1.1) # Element-wise (same as .map()) df["Age_Squared"] = df["Age"].apply(lambda x: x ** 2) ``` ## Performance Comparison ```python import time def measure_time(name, func, *args, **kwargs): start = time.time() result = func(*args, **kwargs) elapsed = time.time() - start print(f"{name}: {elapsed:.4f} seconds") return result large_df = pd.DataFrame({ "A": np.random.randn(1_000_000), "B": np.random.randn(1_000_000), }) # Vectorised operation (fastest) measure_time("Vectorised", lambda: large_df["A"] + large_df["B"]) # .apply() on axis=0 (one function call per column) measure_time("apply axis=0", lambda: large_df[["A", "B"]].apply(np.sum)) # .apply() on axis=1 (one function call per row — slowest) measure_time("apply axis=1", lambda: large_df.apply(lambda row: row["A"] + row["B"], axis=1)) ``` ```{tip} For large DataFrames, prefer vectorised operations (native Pandas/NumPy functions) over `.apply()` whenever possible. `.apply(axis=1)` is particularly slow because it calls Python functions once per row. ``` ## Summary - `.loc[]` for label-based, `.iloc[]` for position-based selection - `.query()` provides clean string-based filtering with `@` for variable references - Boolean indexing with `&`, `|`, `~` for flexible condition-based filtering - `.apply()` applies functions along an axis; `.map()` transforms Series elements - Lambda functions enable concise inline transformations - `.replace()` handles value substitution with dicts, regex, or scalars - Vectorised operations are significantly faster than row-wise `.apply()` ## Exercises Using this DataFrame: ```python import pandas as pd import numpy as np df = pd.DataFrame({ "Product": ["Widget A", "Widget B", "Gadget X", "Gadget Y", "Widget C", "Tool Z"], "Category": ["Widgets", "Widgets", "Gadgets", "Gadgets", "Widgets", "Tools"], "Price": [9.99, 14.99, 24.99, 19.99, 12.99, 49.99], "Quantity": [100, 200, 50, 75, 150, 25], "Rating": [4.5, 3.8, 4.9, 4.2, 3.5, 4.7], }) ``` 1. Use `.loc[]` to select all rows where `Category` is "Gadgets" and only the `Product` and `Price` columns 2. Use `.iloc[]` to select rows 2–4 and columns 0, 2, 3 3. Use `.query()` to find all products with `Price > 15` and `Quantity > 50` 4. Add a column `Total_Value` using `.apply(axis=1)` as `Price * Quantity` 5. Add a column `Category_Code` using `.map()` to convert category names to integers 6. Use `.replace()` to replace "Widgets" with "W", "Gadgets" with "G", "Tools" with "T" 7. Apply a lambda function to create a `Price_Category` column: "Budget" (< $15), "Standard" ($15–$30), "Premium" (> $30) ## Further Reading - [Pandas Indexing and Selecting Data](https://pandas.pydata.org/docs/user_guide/indexing.html) - [Pandas .query() Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.query.html) - [Pandas .apply() Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html)