diff --git a/lab-sql-python-connection.ipynb b/lab-sql-python-connection.ipynb new file mode 100644 index 0000000..875d2c1 --- /dev/null +++ b/lab-sql-python-connection.ipynb @@ -0,0 +1,97 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "2c392e84", + "metadata": {}, + "outputs": [], + "source": [ + "from sqlalchemy import create_engine\n", + "\n", + "# Replace the following with your actual database URI\n", + "DATABASE_URI = 'mysql+pymysql://username:password@localhost:3306/sakila'\n", + "\n", + "# Create engine\n", + "engine = create_engine(DATABASE_URI)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "3acedc81", + "metadata": {}, + "outputs": [], + "source": [ + "import pandas as pd\n", + "\n", + "def rentals_month(engine, month, year):\n", + " query = f\"\"\"\n", + " SELECT \n", + " customer_id, \n", + " COUNT(rental_id) AS rentals\n", + " FROM \n", + " sakila.rental\n", + " WHERE \n", + " MONTH(rental_date) = {month} AND YEAR(rental_date) = {year}\n", + " GROUP BY \n", + " customer_id;\n", + " \"\"\"\n", + " \n", + " # Retrieve data using pandas\n", + " df = pd.read_sql(query, con=engine)\n", + " return df" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "1a7162c2", + "metadata": {}, + "outputs": [], + "source": [ + "def rental_count_month(rental_df, month, year):\n", + " column_name = f'rentals_{str(month).zfill(2)}_{year}'\n", + " rental_df = rental_df.rename(columns={'rentals': column_name})\n", + " return rental_df" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "b26328f9", + "metadata": {}, + "outputs": [], + "source": [ + "def compare_rentals(df1, df2):\n", + " # Merge the two DataFrames on customer_id\n", + " combined_df = pd.merge(df1, df2, on='customer_id', how='outer').fillna(0)\n", + " \n", + " # Create 'difference' column\n", + " combined_df['difference'] = combined_df.iloc[:, 1] - combined_df.iloc[:, 2]\n", + " return combined_df" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "base", + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}