Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 155 additions & 0 deletions lab_connecting_python_to_SQL.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "5ab0d189-4a68-4007-b822-42ef49caa122",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Requirement already satisfied: pymysql in c:\\users\\leysu\\anaconda3\\envs\\anaconda-2025.12-py3.13\\lib\\site-packages (1.2.0)\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"# install pymsql\n",
"%pip install pymysql"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "dc4405f4-4fff-4fc6-8ded-498645eedf85",
"metadata": {},
"outputs": [],
"source": [
"# Step 1: Import Required Libraries\n",
"from sqlalchemy import create_engine\n",
"import pandas as pd"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "0ffa6320-3fd7-41cf-aa6c-f6a1054fd2a8",
"metadata": {},
"outputs": [],
"source": [
"# STEP 2: Establish a connection between python and sakila database\n",
"engine = create_engine(\"mysql+pymysql://root:BABYb@22@localhost/sakila\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "5e7425de-8f94-4f5a-be6d-d5f358faf5ba",
"metadata": {},
"outputs": [],
"source": [
"# STEP 3: write the rentals_month function\n",
"def rentals_month(engine, month: int, year: int) -> pd.DataFrame:\n",
" \"\"\"Retrieves raw rental records for a designated month and year.\"\"\"\n",
" # Write the SQL query\n",
" query = f\"\"\"\n",
" SELECT\n",
" r.rental_id,\n",
" r.rental_date,\n",
" r.inventory_id,\n",
" r.customer_id,\n",
" r.staff_id\n",
" FROM rental AS r\n",
" WHERE MONTH(r.rental_date) = {month}\n",
" AND YEAR(r.rental_date) = {year};\n",
" \"\"\"\n",
" # Executing the query and loading results directly into a DataFrame\n",
" df_rentals = pd.read_sql(query, con=engine)\n",
" return df_rentals"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "ce941b11-da46-44a1-829d-e5eff29373e5",
"metadata": {},
"outputs": [],
"source": [
"# STEP 4: Develop the rental_count_month function\n",
"def rental_count_month(df_rentalas: pd.DataFrame, month: int, year: int) -> pd.DataFrame:\n",
" \"\"\"Aggregates rental data by customer_id and dynamically titles the count column.\"\"\"\n",
"\n",
" # Grouping by customer_id and counting the number of records per group\n",
" df_counts = df_rentals.groupby(\"customer_id\").size().reset_index(name=\"rental_count\")\n",
" \n",
" # Formatting strings to match the requested pattern\n",
" column_name = f\"rentals_{month:02d}_{year}\"\n",
"\n",
" # Renaming the generic count column to the custom dynamic name\n",
" df_counts = df_counts.raname(columns={\"rental_count\": column_name})\n",
"\n",
" return df_counts\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "b0a162fb-b387-4459-b77c-d81d4ec13a80",
"metadata": {},
"outputs": [],
"source": [
"# STEP 5: Create the compare_rentals function\n",
"def compare_rentals(df_month1: pd.DataFrame, df_month2: pd.DataFrame) -> pd.DataFrame:\n",
" \"\"\"Merges two monthly datasets and calculates individual customer rental volume differences.\"\"\"\n",
" \n",
" # Identifying the custom dynamic column names to perform calculations later\n",
" col_m1 = df_month1.columns[1]\n",
" col_m2 = df_month2.columns[1]\n",
" \n",
" # Performing an outer join on customer_id so no customer data is left out\n",
" df_merged = pd.merge(df_month1, df_month2, on=\"customer_id\", how=\"outer\")\n",
" \n",
" # Replacing NaN values with 0 for customers who didn't rent during a specific month\n",
" df_merged[col_m1] = df_merged[col_m1].fillna(0).astype(int)\n",
" df_merged[col_m2] = df_merged[col_m2].fillna(0).astype(int)\n",
" \n",
" # Creating the derived 'difference' field by subtracting Month 1 from Month 2\n",
" df_merged[\"difference\"] = df_merged[col_m2] - df_merged[col_m1]\n",
" \n",
" return df_merged"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ced5f6e9-29b6-49f1-9a22-28934157618a",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "anaconda-2025.12-py3.13",
"language": "python",
"name": "conda-env-anaconda-2025.12-py3.13"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}