From 928dcbd3853ea65217a4e897c79ade3bcba513de Mon Sep 17 00:00:00 2001 From: arnaumatasfont-keky Date: Fri, 1 May 2026 18:12:38 +0200 Subject: [PATCH] Solved lab --- python_sql.ipynb | 213 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 python_sql.ipynb diff --git a/python_sql.ipynb b/python_sql.ipynb new file mode 100644 index 0000000..f409939 --- /dev/null +++ b/python_sql.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Connecting Python to SQL — Sakila Lab\n", + "\n", + "This lab explores the **Sakila** database to identify customers active in both May and June 2005, and compares their rental activity between the two months." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Step 1 — Establish a connection to the Sakila database" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "0972c95a", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Collecting pymysql\n", + " Downloading pymysql-1.1.3-py3-none-any.whl.metadata (4.3 kB)\n", + "Downloading pymysql-1.1.3-py3-none-any.whl (45 kB)\n", + "Installing collected packages: pymysql\n", + "Successfully installed pymysql-1.1.3\n" + ] + } + ], + "source": [ + "!pip install pymysql" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connection successful ✓\n" + ] + } + ], + "source": [ + "import pandas as pd\n", + "from sqlalchemy import create_engine\n", + "\n", + "DB_USER = 'root'\n", + "DB_PASSWORD = '69696363Aasql7'\n", + "DB_HOST = 'localhost'\n", + "DB_PORT = '3306'\n", + "DB_NAME = 'sakila'\n", + "\n", + "engine = create_engine(\n", + " f'mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'\n", + ")\n", + "with engine.connect() as conn:\n", + " print('Connection successful ✓')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a61246da", + "metadata": {}, + "outputs": [], + "source": [ + "#2. Write a Python function called `rentals_month` that retrieves rental data for a given month and year (passed as parameters) from the Sakila database as a Pandas DataFrame. The function should take in three parameters:\n", + "\n", + "\t#- `engine`: an object representing the database connection engine to be used to establish a connection to the Sakila database.\n", + "\t#- `month`: an integer representing the month for which rental data is to be retrieved.\n", + "\t#- `year`: an integer representing the year for which rental data is to be retrieved.\n", + "\n", + "\t#The function should execute a SQL query to retrieve the rental data for the specified month and year from the rental table in the Sakila database, and return it as a pandas DataFrame.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "aed3e51b", + "metadata": {}, + "outputs": [], + "source": [ + "def rentals_month(engine, month, year):\n", + " query = \"\"\"\n", + " SELECT *\n", + " FROM rental\n", + " WHERE MONTH(rental_date) = %(month)s\n", + " AND YEAR(rental_date) = %(year)s\n", + " \"\"\"\n", + " df = pd.read_sql(query, engine, params={\"month\": month, \"year\": year})\n", + " return df" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed0251a9", + "metadata": {}, + "outputs": [], + "source": [ + "#3. \"Develop a Python function called `rental_count_month` that takes the DataFrame provided by `rentals_month` as input along with the month and year and returns a new DataFrame containing the number of rentals made by each customer_id during the selected month and year. \n", + "\t#The function should also include the month and year as parameters and use them to name the new column according to the month and year, for example, if the input month is 05 and the year is 2005, the column name should be \"rentals_05_2005\".\n", + "\n", + "\n", + "\t#*Hint: Consider making use of pandas [groupby()](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html)*" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d641ff79", + "metadata": {}, + "outputs": [], + "source": [ + "def rental_count_month(df, month, year):\n", + " col_name = f'rentals_{month:02d}_{year}'\n", + " result = df.groupby('customer_id').size().reset_index(name=col_name)\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a5718857", + "metadata": {}, + "outputs": [], + "source": [ + "#4. Create a Python function called `compare_rentals` that takes two DataFrames as input containing the number of rentals made by each customer in different months and years. \n", + "#The function should return a combined DataFrame with a new 'difference' column, which is the difference between the number of rentals in the two months." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "b354dfec", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "\n", + "def compare_rentals(df1, df2):\n", + " combined = df1.merge(df2, on =\"customer_id\", how =\"outer\").fillna(0)\n", + " col1 = df1.columns[1]\n", + " col2 = df2.columns[1]\n", + " combined['difference'] = combined[col1] - combined[col2]\n", + " return combined" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "e04c887c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " customer_id rentals_05_2005 rentals_06_2005 difference\n", + "0 1 2.0 7.0 -5.0\n", + "1 2 1.0 1.0 0.0\n", + "2 3 2.0 4.0 -2.0\n", + "3 4 0.0 6.0 -6.0\n", + "4 5 3.0 5.0 -2.0\n" + ] + } + ], + "source": [ + "#llamamos funciones\n", + "df_may_2005 = rentals_month(engine, 5, 2005)\n", + "df_june_2005 = rentals_month(engine, 6, 2005)\n", + "\n", + "df_may_count = rental_count_month(df_may_2005, 5, 2005)\n", + "df_june_count = rental_count_month(df_june_2005, 6, 2005)\n", + "\n", + "df_result = compare_rentals(df_may_count, df_june_count)\n", + "print(df_result.head())" + ] + } + ], + "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 +}