{ "cells": [ { "cell_type": "markdown", "id": "3f849166", "metadata": {}, "source": [ "# 🏋️ Pandas Practice Exercise 1: Core Fundamentals & Practical Operations\n", "\n", "This notebook contains **20 progressive, practical problems** designed to build confidence and muscle memory with Pandas:\n", "- Creating Series & DataFrames from scratch\n", "- Indexing, selecting, and slicing (`loc` vs `iloc`)\n", "- Querying and filtering data\n", "- Adding, renaming, and dropping columns\n", "- Handling missing data (NaNs)\n", "- Sorting, descriptive statistics, and counting\n", "- GroupBy split-apply-combine aggregations\n", "- Vectorized string methods and datetime parsing\n", "\n", "### 📝 Instructions:\n", "1. Write your code in the provided code cells under each problem.\n", "2. Run your code to verify that it outputs the expected result.\n", "3. Compare your code with the companion solutions notebook: `03_pandas_exercise_1_solutions.ipynb`." ] }, { "cell_type": "markdown", "id": "f878e556", "metadata": {}, "source": [ "### Problem 1: Import Pandas and Check Version\n", "\n", "Import pandas with the alias `pd` and numpy as `np`. Print their installed versions." ] }, { "cell_type": "code", "execution_count": null, "id": "bd3869c9", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "\n", "# Print versions below\n" ] }, { "cell_type": "markdown", "id": "969b1898", "metadata": {}, "source": [ "### Problem 2: Create a Series with Custom Index\n", "\n", "Create a `pd.Series` containing the populations (in millions) of five cities: `{'Tokyo': 37.4, 'Delhi': 29.3, 'Shanghai': 26.3, 'Sao Paulo': 21.8, 'Mexico City': 21.6}`. Give the Series the name `'Population_M'`." ] }, { "cell_type": "code", "execution_count": null, "id": "1d329edf", "metadata": {}, "outputs": [], "source": [ "# Create and print the Series\n" ] }, { "cell_type": "markdown", "id": "13adf9d9", "metadata": {}, "source": [ "### Problem 3: Create a DataFrame from a Dictionary\n", "\n", "Create a DataFrame `students_df` representing 5 students with the following columns:\n", "- `'Name'`: `['Alice', 'Bob', 'Charlie', 'Diana', 'Evan']`\n", "- `'Age'`: `[20, 22, 21, 23, 20]`\n", "- `'Major'`: `['CS', 'Math', 'Physics', 'CS', 'Biology']`\n", "- `'GPA'`: `[3.8, 3.2, 3.9, 2.9, 3.5]`\n", "- `'Passed'`: `[True, True, True, False, True]`" ] }, { "cell_type": "code", "execution_count": null, "id": "d2b33d4b", "metadata": {}, "outputs": [], "source": [ "# Create students_df\n", "students_df = None\n" ] }, { "cell_type": "markdown", "id": "1f3f4355", "metadata": {}, "source": [ "### Problem 4: Inspect DataFrame Dimensions and Data Types\n", "\n", "Using `students_df`, print:\n", "1. The total number of rows and columns (shape)\n", "2. The column names\n", "3. The data type (`dtype`) of each column\n", "4. A summary of non-null counts and memory using `.info()`" ] }, { "cell_type": "code", "execution_count": null, "id": "baee1bfe", "metadata": {}, "outputs": [], "source": [ "# Inspect students_df\n" ] }, { "cell_type": "markdown", "id": "cbb6f02f", "metadata": {}, "source": [ "### Problem 5: Series vs DataFrame Column Selection\n", "\n", "1. Extract the `'GPA'` column as a 1D `Series` and store it in `gpa_series`.\n", "2. Extract the `'Name'` and `'GPA'` columns as a 2D `DataFrame` and store it in `name_gpa_df`.\n", "3. Print the types of both variables." ] }, { "cell_type": "code", "execution_count": null, "id": "2efe58e7", "metadata": {}, "outputs": [], "source": [ "# Select columns as Series and DataFrame\n" ] }, { "cell_type": "markdown", "id": "aa420fc9", "metadata": {}, "source": [ "### Problem 6: Positional Slicing with .iloc\n", "\n", "Using `students_df`:\n", "1. Select the first 3 rows and the first 3 columns using `.iloc`.\n", "2. Select the very last row using negative integer indexing." ] }, { "cell_type": "code", "execution_count": null, "id": "d3465a34", "metadata": {}, "outputs": [], "source": [ "# Use .iloc\n" ] }, { "cell_type": "markdown", "id": "96465302", "metadata": {}, "source": [ "### Problem 7: Label-Based Selection with .loc\n", "\n", "1. Create a new DataFrame `df_named` by setting `'Name'` as the index of `students_df`.\n", "2. Use `.loc` to retrieve the `'Major'` and `'GPA'` for `'Charlie'`.\n", "3. Slice from `'Bob'` to `'Diana'` (inclusive) for all columns." ] }, { "cell_type": "code", "execution_count": null, "id": "471d4c96", "metadata": {}, "outputs": [], "source": [ "# Use .set_index and .loc\n" ] }, { "cell_type": "markdown", "id": "ba491223", "metadata": {}, "source": [ "### Problem 8: Single Condition Filtering\n", "\n", "Filter `students_df` to find all students who have a `'GPA'` strictly greater than `3.4`." ] }, { "cell_type": "code", "execution_count": null, "id": "ee1e2be8", "metadata": {}, "outputs": [], "source": [ "# Filter GPA > 3.4\n" ] }, { "cell_type": "markdown", "id": "35f74673", "metadata": {}, "source": [ "### Problem 9: Multi-Condition Filtering with Logical Operators\n", "\n", "Find all students who satisfy BOTH conditions:\n", "- `'Major'` is `'CS'`\n", "- `'Passed'` is `True`\n", "Remember to use the `&` operator and enclose conditions in parentheses `()`." ] }, { "cell_type": "code", "execution_count": null, "id": "bf1de8cb", "metadata": {}, "outputs": [], "source": [ "# CS and Passed\n" ] }, { "cell_type": "markdown", "id": "ebb1a0b1", "metadata": {}, "source": [ "### Problem 10: Filtering with .isin() and .between()\n", "\n", "1. Find all students whose `'Major'` is either `'Math'` or `'Physics'` using `.isin()`.\n", "2. Find all students whose `'Age'` is between 21 and 23 (inclusive) using `.between()`." ] }, { "cell_type": "code", "execution_count": null, "id": "b6f1f864", "metadata": {}, "outputs": [], "source": [ "# Use .isin() and .between()\n" ] }, { "cell_type": "markdown", "id": "9cebf994", "metadata": {}, "source": [ "### Problem 11: Add Calculated Columns (Vectorized)\n", "\n", "Add two new columns to a copy of `students_df`:\n", "1. `'GPA_Percentage'`: Convert the 4.0 GPA scale to percentage (`GPA / 4.0 * 100`).\n", "2. `'Honors'`: Boolean column indicating whether `GPA >= 3.8`." ] }, { "cell_type": "code", "execution_count": null, "id": "eed04fa8", "metadata": {}, "outputs": [], "source": [ "# Add calculated columns\n" ] }, { "cell_type": "markdown", "id": "48dd2e45", "metadata": {}, "source": [ "### Problem 12: Renaming Columns\n", "\n", "Rename `'Major'` to `'Field_of_Study'` and `'Passed'` to `'Graduation_Ready'` in `students_df`." ] }, { "cell_type": "code", "execution_count": null, "id": "88820efc", "metadata": {}, "outputs": [], "source": [ "# Rename columns\n" ] }, { "cell_type": "markdown", "id": "28b707ad", "metadata": {}, "source": [ "### Problem 13: Dropping Columns Safely\n", "\n", "Drop the `'Passed'` column from `students_df` without modifying the original in-place. Verify that the original `students_df` still has all 5 columns." ] }, { "cell_type": "code", "execution_count": null, "id": "dc9310c3", "metadata": {}, "outputs": [], "source": [ "# Drop column\n" ] }, { "cell_type": "markdown", "id": "ee62902a", "metadata": {}, "source": [ "### Problem 14: Detecting Missing Data\n", "\n", "Consider this dataset with missing values:\n", "```python\n", "exam_data = {\n", " 'Student': ['Sam', 'Alex', 'Jordan', 'Taylor', 'Morgan'],\n", " 'Midterm': [85.0, np.nan, 90.0, 72.0, np.nan],\n", " 'Final': [88.0, 79.0, np.nan, 68.0, 95.0],\n", " 'Attendance': [95, 80, 85, np.nan, 90]\n", "}\n", "exam_df = pd.DataFrame(exam_data)\n", "```\n", "1. Count total missing values (`NaN`) per column.\n", "2. Print the total number of missing values in the entire DataFrame." ] }, { "cell_type": "code", "execution_count": null, "id": "4fe8f199", "metadata": {}, "outputs": [], "source": [ "exam_data = {\n", " 'Student': ['Sam', 'Alex', 'Jordan', 'Taylor', 'Morgan'],\n", " 'Midterm': [85.0, np.nan, 90.0, 72.0, np.nan],\n", " 'Final': [88.0, 79.0, np.nan, 68.0, 95.0],\n", " 'Attendance': [95, 80, 85, np.nan, 90]\n", "}\n", "exam_df = pd.DataFrame(exam_data)\n", "\n", "# Count missing values\n" ] }, { "cell_type": "markdown", "id": "88a6876c", "metadata": {}, "source": [ "### Problem 15: Imputing Missing Values\n", "\n", "Fill the missing values in `exam_df`:\n", "1. Fill missing `'Midterm'` scores with the average (mean) of the existing Midterm scores.\n", "2. Fill missing `'Final'` scores with the median of existing Final scores.\n", "3. Fill missing `'Attendance'` with `100`." ] }, { "cell_type": "code", "execution_count": null, "id": "c73ec9ee", "metadata": {}, "outputs": [], "source": [ "# Impute missing values in exam_df\n" ] }, { "cell_type": "markdown", "id": "7579050c", "metadata": {}, "source": [ "### Problem 16: Sorting Values & Resetting Index\n", "\n", "Using `students_df`:\n", "1. Sort students by `'GPA'` descending (highest GPA first).\n", "2. Reset the row index so it starts cleanly from `0, 1, 2, ...`.\n", "3. Print the top 3 students." ] }, { "cell_type": "code", "execution_count": null, "id": "e7b4cf76", "metadata": {}, "outputs": [], "source": [ "# Sort by GPA descending and reset index\n" ] }, { "cell_type": "markdown", "id": "2d78a5ca", "metadata": {}, "source": [ "### Problem 17: Summary Statistics and Value Counts\n", "\n", "Using `students_df`:\n", "1. Compute the mean, median, min, max, and standard deviation of `'GPA'`.\n", "2. Count how many students belong to each `'Major'` using `.value_counts()`.\n", "3. Calculate the percentage of students in each major." ] }, { "cell_type": "code", "execution_count": null, "id": "f7dff6a4", "metadata": {}, "outputs": [], "source": [ "# Summary statistics and value counts\n" ] }, { "cell_type": "markdown", "id": "0e9a8627", "metadata": {}, "source": [ "### Problem 18: GroupBy Single Column Aggregation\n", "\n", "Group `students_df` by `'Major'` and compute the average `'GPA'` and average `'Age'` for each major." ] }, { "cell_type": "code", "execution_count": null, "id": "370399b2", "metadata": {}, "outputs": [], "source": [ "# Groupby Major\n" ] }, { "cell_type": "markdown", "id": "a9fb6551", "metadata": {}, "source": [ "### Problem 19: Named Aggregations with .groupby().agg()\n", "\n", "Group `students_df` by `'Major'` and compute:\n", "1. `'Student_Count'`: total number of students in that major (`count`)\n", "2. `'Avg_GPA'`: average GPA in that major (`mean`)\n", "3. `'Highest_GPA'`: highest GPA in that major (`max`)\n", "Reset the index so `'Major'` becomes a regular column." ] }, { "cell_type": "code", "execution_count": null, "id": "c394165f", "metadata": {}, "outputs": [], "source": [ "# Named aggregation\n" ] }, { "cell_type": "markdown", "id": "26a47672", "metadata": {}, "source": [ "### Problem 20: String Manipulation and Datetime Parsing\n", "\n", "Given the following enrollment log:\n", "```python\n", "logs_data = {\n", " 'Raw_Student': [' ALICE ', 'bob smith', ' CHARLIE brown ', 'diana '],\n", " 'Date_Enrolled': ['2026-01-10', '2026-02-15', '2026-03-01', '2026-03-22']\n", "}\n", "logs_df = pd.DataFrame(logs_data)\n", "```\n", "1. Clean `'Raw_Student'` by trimming whitespace and capitalizing each word to Title Case.\n", "2. Convert `'Date_Enrolled'` to datetime objects.\n", "3. Extract the `'Month_Name'` and `'Day_of_Week'` into new columns." ] }, { "cell_type": "code", "execution_count": null, "id": "867af8d6", "metadata": {}, "outputs": [], "source": [ "logs_data = {\n", " 'Raw_Student': [' ALICE ', 'bob smith', ' CHARLIE brown ', 'diana '],\n", " 'Date_Enrolled': ['2026-01-10', '2026-02-15', '2026-03-01', '2026-03-22']\n", "}\n", "logs_df = pd.DataFrame(logs_data)\n", "\n", "# Clean strings and parse dates\n" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }