# Module 4: Introduction to Pandas ## Learning Objectives By the end of this module, you will be able to: - Import Pandas and understand its core data structures - Create and manipulate Series objects - Create and inspect DataFrame objects - Work with Index and Columns - Select, filter, and sort data using multiple techniques --- ## Importing Pandas By convention, Pandas is imported with the alias `pd`: ```python import pandas as pd import numpy as np ``` ```{note} NumPy is the numerical foundation underneath Pandas. Many Pandas operations return NumPy arrays or accept NumPy-compatible inputs. ``` ## Pandas Core Data Structures | Structure | Dimensions | Description | |-----------|-----------|-------------| | **Series** | 1D | Labelled array, like a column in a spreadsheet | | **DataFrame** | 2D | Tabular data with rows and columns, like a spreadsheet or SQL table | ## Series A Series is a one-dimensional labelled array that can hold any data type. ### Creating a Series ```python # From a list s1 = pd.Series([10, 20, 30, 40, 50]) # From a list with custom index s2 = pd.Series([10, 20, 30, 40, 50], index=["a", "b", "c", "d", "e"]) # From a dictionary s3 = pd.Series({"a": 10, "b": 20, "c": 30}) # With a name s4 = pd.Series([1, 2, 3], name="scores") print(s2) ``` **Output:** ``` a 10 b 20 c 30 d 40 e 50 dtype: int64 ``` ### Accessing Series data ```python print(s2["b"]) # 20 — by label print(s2[0]) # 10 — by position print(s2[["a", "c", "e"]]) # Fancy indexing print(s2[s2 > 25]) # Boolean indexing ``` ```{tip} Use `.iloc[]` for positional indexing and `.loc[]` for label-based indexing — this avoids ambiguity when the index contains integers. ``` ### Series operations ```python print(s2 * 2) # Vectorised multiplication print(s2.mean()) # 30.0 print(s2.sum()) # 150 print(s2.describe()) # Summary statistics print(s2.apply(lambda x: x ** 2)) # Apply a function ``` ## DataFrame A DataFrame is a two-dimensional labelled data structure with columns of potentially different types. ### Creating a DataFrame ```python # From a dictionary of lists data = { "Name": ["Alice", "Bob", "Charlie", "Diana"], "Age": [25, 30, 35, 28], "Salary": [50000, 60000, 70000, 55000], "Department": ["HR", "IT", "IT", "HR"], } df = pd.DataFrame(data) print(df) ``` **Output:** ``` Name Age Salary Department 0 Alice 25 50000 HR 1 Bob 30 60000 IT 2 Charlie 35 70000 IT 3 Diana 28 55000 HR ``` ### From other sources ```python # From a list of dictionaries df2 = pd.DataFrame([ {"Name": "Alice", "Age": 25}, {"Name": "Bob", "Age": 30}, ]) # From a NumPy array df3 = pd.DataFrame( np.random.randn(5, 3), columns=["A", "B", "C"], index=pd.date_range("2024-01-01", periods=5), ) # From a CSV file # df = pd.read_csv("data.csv") ``` ## The Index The Index is a fundamental Pandas object that labels rows. ```python print(df.index) # RangeIndex(start=0, stop=4, step=1) print(df.columns) # Index(['Name', 'Age', 'Salary', 'Department'], dtype='object') # Custom index df_custom = df.set_index("Name") print(df_custom) ``` **Output:** ``` Age Salary Department Name Alice 25 50000 HR Bob 30 60000 IT Charlie 35 70000 IT Diana 28 55000 HR ``` ```{warning} Setting a meaningful index (e.g., dates or IDs) often makes data alignment and joining more efficient. However, the default `RangeIndex` is perfectly fine for most analytical workflows. ``` ## Columns ```python # Select a single column (returns a Series) print(df["Name"]) print(df.Name) # Attribute access (works for valid Python identifiers) # Select multiple columns (returns a DataFrame) print(df[["Name", "Salary"]]) # Rename columns df_renamed = df.rename(columns={"Name": "Employee", "Salary": "Compensation"}) ``` ## Selecting Data ### Using `[]` operator ```python # Select rows by slice print(df[1:3]) # Rows 1 and 2 (exclusive of 3) # Select columns print(df[["Name", "Age"]]) ``` ### Using `.loc[]` (label-based) ```python # Single row by label print(df.loc[0]) # Multiple rows print(df.loc[0:2]) # Inclusive of 2 # Specific rows and columns print(df.loc[0:2, ["Name", "Salary"]]) # Boolean condition print(df.loc[df["Age"] > 28]) ``` ### Using `.iloc[]` (position-based) ```python print(df.iloc[0]) # First row print(df.iloc[1:3]) # Rows 1 and 2 print(df.iloc[1:3, 0:2]) # Rows 1-2, columns 0-1 print(df.iloc[:, [0, 2]]) # All rows, columns 0 and 2 ``` ```{note} `.loc[]` is inclusive of the end label. `.iloc[]` follows standard Python exclusive end semantics. ``` ## Filtering Data ```python # Boolean mask mask = df["Age"] > 28 print(df[mask]) # Multiple conditions print(df[(df["Age"] > 25) & (df["Department"] == "IT")]) # Using .query() — clean string-based filtering print(df.query("Age > 25 and Department == 'IT'")) # Using .isin() it_hr = df[df["Department"].isin(["IT", "HR"])] # Using .between() middle_aged = df[df["Age"].between(25, 32)] ``` ## Sorting Data ```python # Sort by a single column df_sorted = df.sort_values("Age", ascending=False) # Sort by multiple columns df_sorted = df.sort_values(["Department", "Salary"], ascending=[True, False]) # Sort by index df_sorted_idx = df.set_index("Name").sort_index() print(df_sorted.head()) ``` ## chaining Methods Pandas supports method chaining — a powerful technique for building readable data pipelines: ```python result = ( df[df["Age"] > 25] .sort_values("Salary", ascending=False) .loc[:, ["Name", "Salary"]] .rename(columns={"Salary": "Compensation"}) ) ``` ```{tip} Method chaining produces more readable code by avoiding intermediate variables. Use parentheses `()` to break chains across multiple lines. ``` ## Summary - Series are 1D labelled arrays; DataFrames are 2D labelled tables - The Index labels rows; Columns labels columns - `.loc[]` uses labels (inclusive), `.iloc[]` uses positions (exclusive) - Boolean masks enable powerful row filtering - `.sort_values()` orders data by one or more columns - Method chaining creates clean, readable data pipelines ## Exercises Using the following DataFrame: ```python import pandas as pd data = { "Product": ["Widget A", "Widget B", "Widget C", "Widget D", "Widget E"], "Price": [9.99, 14.99, 24.99, 4.99, 19.99], "Quantity": [100, 200, 50, 300, 150], "Category": ["Tools", "Tools", "Garden", "Garden", "Tools"], } df = pd.DataFrame(data) ``` 1. Select all products with `Price > 15` 2. Select all `Garden` category products where `Quantity > 100` 3. Sort the DataFrame by `Price` descending, then by `Quantity` ascending 4. Use `.loc[]` to select the second, third, and fourth rows and the `Product` and `Price` columns 5. Use `.query()` to find all `Tools` products with a price between $10 and $20 ## Further Reading - [Pandas Series Documentation](https://pandas.pydata.org/docs/reference/api/pandas.Series.html) - [Pandas DataFrame Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) - [10 Minutes to Pandas](https://pandas.pydata.org/docs/user_guide/10min.html)