From 27893978e3319a2c6e1d28ad31148b36304812ec Mon Sep 17 00:00:00 2001 From: Desmond Ugboaja Date: Wed, 29 Apr 2026 00:56:11 +0200 Subject: [PATCH] Solved lab --- SQL to Python Completed.ipynb | 123 ++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 SQL to Python Completed.ipynb diff --git a/SQL to Python Completed.ipynb b/SQL to Python Completed.ipynb new file mode 100644 index 0000000..7251401 --- /dev/null +++ b/SQL to Python Completed.ipynb @@ -0,0 +1,123 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "63e401db", + "metadata": {}, + "source": [ + "Importing from SQL" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "bbab3725", + "metadata": {}, + "outputs": [], + "source": [ + "from sqlalchemy import create_engine\n", + "import pandas as pd\n", + "\n", + "engine = create_engine(\"mysql+pymysql://username:Desmond123.@localhost/sakila\")" + ] + }, + { + "cell_type": "markdown", + "id": "83d70774", + "metadata": {}, + "source": [ + "query rental rows " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "1c0f78d1", + "metadata": {}, + "outputs": [], + "source": [ + "def rentals_month(engine, month, year):\n", + " query = f\"\"\"\n", + " SELECT rental_id, rental_date, inventory_id, customer_id, staff_id\n", + " FROM rental\n", + " WHERE MONTH(rental_date) = {month}\n", + " AND YEAR(rental_date) = {year}\n", + " \"\"\"\n", + " df = pd.read_sql(query, engine)\n", + " return df" + ] + }, + { + "cell_type": "markdown", + "id": "ee97fed0", + "metadata": {}, + "source": [ + "counting rentals per customer." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "1cc1f59d", + "metadata": {}, + "outputs": [], + "source": [ + "def rental_count_month(df, month, year):\n", + " column_name = f\"rentals_{month:02d}_{year}\"\n", + " \n", + " result = (\n", + " df.groupby(\"customer_id\")\n", + " .size()\n", + " .reset_index(name=column_name)\n", + " )\n", + " \n", + " return result" + ] + }, + { + "cell_type": "markdown", + "id": "7ddc8784", + "metadata": {}, + "source": [ + "merging the monthly summaries" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "f22bf80c", + "metadata": {}, + "outputs": [], + "source": [ + "def compare_rentals(df1, df2):\n", + " merged = pd.merge(df1, df2, on=\"customer_id\", how=\"inner\")\n", + " \n", + " rental_cols = [col for col in merged.columns if col != \"customer_id\"]\n", + " merged[\"difference\"] = merged[rental_cols[1]] - merged[rental_cols[0]]\n", + " \n", + " return merged" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "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.13" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}