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
117 changes: 117 additions & 0 deletions python_connection.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "6611acf4",
"metadata": {},
"outputs": [],
"source": [
"from sqlalchemy import create_engine\n",
"import pandas as pd\n",
"\n",
"def create_db_engine(user, password, host=\"localhost\", port=3306, database=\"sakila\"):\n",
" connection_string = f\"mysql+pymysql://{user}:{password}@{host}:{port}/{database}\"\n",
" engine = create_engine(connection_string)\n",
" return engine\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "743212f6",
"metadata": {},
"outputs": [],
"source": [
"engine = create_db_engine(\"root\", \"your_password\")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bda56806",
"metadata": {},
"outputs": [],
"source": [
"def rentals_month(engine, month, year):\n",
" query = f\"\"\"\n",
" SELECT\n",
" rental_id,\n",
" customer_id,\n",
" rental_date\n",
" FROM rental\n",
" WHERE MONTH(rental_date) = {month}\n",
" AND YEAR(rental_date) = {year};\n",
" \"\"\"\n",
" \n",
" df = pd.read_sql(query, engine)\n",
" return df\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ab263820",
"metadata": {},
"outputs": [],
"source": [
"def rental_count_month(df, month, year):\n",
" \n",
" column_name = f\"rentals_{month:02d}_{year}\"\n",
" \n",
" rental_count = (\n",
" df.groupby(\"customer_id\")\n",
" .size()\n",
" .reset_index(name=column_name)\n",
" )\n",
" \n",
" return rental_count\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "33d006c3",
"metadata": {},
"outputs": [],
"source": [
"def compare_rentals(df1, df2):\n",
" \n",
" combined = pd.merge(\n",
" df1,\n",
" df2,\n",
" on=\"customer_id\",\n",
" how=\"outer\"\n",
" ).fillna(0)\n",
" \n",
" # Identificar automaticamente colunas de rentals\n",
" rental_cols = [col for col in combined.columns if col.startswith(\"rentals_\")]\n",
" \n",
" combined[\"difference\"] = combined[rental_cols[1]] - combined[rental_cols[0]]\n",
" \n",
" return combined\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "167c84eb",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.13.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}