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
97 changes: 97 additions & 0 deletions lab-sql-python-connection.ipynb
Original file line number Diff line number Diff line change
@@ -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
}