diff --git a/lab-dw-aggregating.ipynb b/lab-dw-aggregating.ipynb index fff3ae5..dd6cfb8 100644 --- a/lab-dw-aggregating.ipynb +++ b/lab-dw-aggregating.ipynb @@ -1,161 +1,711 @@ { - "cells": [ - { - "cell_type": "markdown", - "id": "31969215-2a90-4d8b-ac36-646a7ae13744", - "metadata": { - "id": "31969215-2a90-4d8b-ac36-646a7ae13744" - }, - "source": [ - "# Lab | Data Aggregation and Filtering" - ] - }, - { - "cell_type": "markdown", - "id": "a8f08a52-bec0-439b-99cc-11d3809d8b5d", - "metadata": { - "id": "a8f08a52-bec0-439b-99cc-11d3809d8b5d" - }, - "source": [ - "In this challenge, we will continue to work with customer data from an insurance company. We will use the dataset called marketing_customer_analysis.csv, which can be found at the following link:\n", - "\n", - "https://raw.githubusercontent.com/data-bootcamp-v4/data/main/marketing_customer_analysis.csv\n", - "\n", - "This dataset contains information such as customer demographics, policy details, vehicle information, and the customer's response to the last marketing campaign. Our goal is to explore and analyze this data by first performing data cleaning, formatting, and structuring." - ] - }, - { - "cell_type": "markdown", - "id": "9c98ddc5-b041-4c94-ada1-4dfee5c98e50", - "metadata": { - "id": "9c98ddc5-b041-4c94-ada1-4dfee5c98e50" - }, - "source": [ - "1. Create a new DataFrame that only includes customers who have a total_claim_amount greater than $1,000 and have a response of \"Yes\" to the last marketing campaign." - ] - }, + "cells": [ + { + "cell_type": "markdown", + "id": "31969215-2a90-4d8b-ac36-646a7ae13744", + "metadata": { + "id": "31969215-2a90-4d8b-ac36-646a7ae13744" + }, + "source": [ + "# Lab | Data Aggregation and Filtering" + ] + }, + { + "cell_type": "markdown", + "id": "a8f08a52-bec0-439b-99cc-11d3809d8b5d", + "metadata": { + "id": "a8f08a52-bec0-439b-99cc-11d3809d8b5d" + }, + "source": [ + "In this challenge, we will continue to work with customer data from an insurance company. We will use the dataset called marketing_customer_analysis.csv, which can be found at the following link:\n", + "\n", + "https://raw.githubusercontent.com/data-bootcamp-v4/data/main/marketing_customer_analysis.csv\n", + "\n", + "This dataset contains information such as customer demographics, policy details, vehicle information, and the customer's response to the last marketing campaign. Our goal is to explore and analyze this data by first performing data cleaning, formatting, and structuring." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "eceb2c32-64a4-4b83-b1d6-20e3426e4169", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "b9be383e-5165-436e-80c8-57d4c757c8c3", - "metadata": { - "id": "b9be383e-5165-436e-80c8-57d4c757c8c3" - }, - "source": [ - "2. Using the original Dataframe, analyze the average total_claim_amount by each policy type and gender for customers who have responded \"Yes\" to the last marketing campaign. Write your conclusions." + "data": { + "text/html": [ + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Unnamed: 0CustomerStateCustomer Lifetime ValueResponseCoverageEducationEffective To DateEmploymentStatusGender...Number of Open ComplaintsNumber of PoliciesPolicy TypePolicyRenew Offer TypeSales ChannelTotal Claim AmountVehicle ClassVehicle SizeVehicle Type
00DK49336Arizona4809.216960NoBasicCollege2/18/11EmployedM...0.09Corporate AutoCorporate L3Offer3Agent292.800000Four-Door CarMedsizeNaN
11KX64629California2228.525238NoBasicCollege1/18/11UnemployedF...0.01Personal AutoPersonal L3Offer4Call Center744.924331Four-Door CarMedsizeNaN
22LZ68649Washington14947.917300NoBasicBachelor2/10/11EmployedM...0.02Personal AutoPersonal L3Offer3Call Center480.000000SUVMedsizeA
33XL78013Oregon22332.439460YesExtendedCollege1/11/11EmployedM...0.02Corporate AutoCorporate L3Offer2Branch484.013411Four-Door CarMedsizeA
44QA50777Oregon9025.067525NoPremiumBachelor1/17/11Medical LeaveF...NaN7Personal AutoPersonal L2Offer1Branch707.925645Four-Door CarMedsizeNaN
\n", + "

5 rows × 26 columns

\n", + "
" + ], + "text/plain": [ + " Unnamed: 0 Customer State Customer Lifetime Value Response \\\n", + "0 0 DK49336 Arizona 4809.216960 No \n", + "1 1 KX64629 California 2228.525238 No \n", + "2 2 LZ68649 Washington 14947.917300 No \n", + "3 3 XL78013 Oregon 22332.439460 Yes \n", + "4 4 QA50777 Oregon 9025.067525 No \n", + "\n", + " Coverage Education Effective To Date EmploymentStatus Gender ... \\\n", + "0 Basic College 2/18/11 Employed M ... \n", + "1 Basic College 1/18/11 Unemployed F ... \n", + "2 Basic Bachelor 2/10/11 Employed M ... \n", + "3 Extended College 1/11/11 Employed M ... \n", + "4 Premium Bachelor 1/17/11 Medical Leave F ... \n", + "\n", + " Number of Open Complaints Number of Policies Policy Type Policy \\\n", + "0 0.0 9 Corporate Auto Corporate L3 \n", + "1 0.0 1 Personal Auto Personal L3 \n", + "2 0.0 2 Personal Auto Personal L3 \n", + "3 0.0 2 Corporate Auto Corporate L3 \n", + "4 NaN 7 Personal Auto Personal L2 \n", + "\n", + " Renew Offer Type Sales Channel Total Claim Amount Vehicle Class \\\n", + "0 Offer3 Agent 292.800000 Four-Door Car \n", + "1 Offer4 Call Center 744.924331 Four-Door Car \n", + "2 Offer3 Call Center 480.000000 SUV \n", + "3 Offer2 Branch 484.013411 Four-Door Car \n", + "4 Offer1 Branch 707.925645 Four-Door Car \n", + "\n", + " Vehicle Size Vehicle Type \n", + "0 Medsize NaN \n", + "1 Medsize NaN \n", + "2 Medsize A \n", + "3 Medsize A \n", + "4 Medsize NaN \n", + "\n", + "[5 rows x 26 columns]" ] - }, + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import pandas as pd\n", + "url = \"https://raw.githubusercontent.com/data-bootcamp-v4/data/main/marketing_customer_analysis.csv\"\n", + "df = pd.read_csv(url)\n", + "df.head()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "c6df7f39-6f15-46c6-9673-4674188e1e20", + "metadata": { + "scrolled": true + }, + "outputs": [ { - "cell_type": "markdown", - "id": "7050f4ac-53c5-4193-a3c0-8699b87196f0", - "metadata": { - "id": "7050f4ac-53c5-4193-a3c0-8699b87196f0" - }, - "source": [ - "3. Analyze the total number of customers who have policies in each state, and then filter the results to only include states where there are more than 500 customers." - ] - }, + "name": "stdout", + "output_type": "stream", + "text": [ + "Index(['Unnamed: 0', 'Customer', 'State', 'Customer Lifetime Value',\n", + " 'Response', 'Coverage', 'Education', 'Effective To Date',\n", + " 'EmploymentStatus', 'Gender', 'Income', 'Location Code',\n", + " 'Marital Status', 'Monthly Premium Auto', 'Months Since Last Claim',\n", + " 'Months Since Policy Inception', 'Number of Open Complaints',\n", + " 'Number of Policies', 'Policy Type', 'Policy', 'Renew Offer Type',\n", + " 'Sales Channel', 'Total Claim Amount', 'Vehicle Class', 'Vehicle Size',\n", + " 'Vehicle Type'],\n", + " dtype='object')\n" + ] + } + ], + "source": [ + "print(df.columns)" + ] + }, + { + "cell_type": "markdown", + "id": "9c98ddc5-b041-4c94-ada1-4dfee5c98e50", + "metadata": { + "id": "9c98ddc5-b041-4c94-ada1-4dfee5c98e50" + }, + "source": [ + "1. Create a new DataFrame that only includes customers who have a total_claim_amount greater than $1,000 and have a response of \"Yes\" to the last marketing campaign." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "e7822ee9-c4d8-4446-851b-ccb3b4f40da1", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "b60a4443-a1a7-4bbf-b78e-9ccdf9895e0d", - "metadata": { - "id": "b60a4443-a1a7-4bbf-b78e-9ccdf9895e0d" - }, - "source": [ - "4. Find the maximum, minimum, and median customer lifetime value by education level and gender. Write your conclusions." - ] - }, + "name": "stdout", + "output_type": "stream", + "text": [ + " Unnamed: 0 Customer State Customer Lifetime Value Response \\\n", + "189 189 OK31456 California 11009.130490 Yes \n", + "236 236 YJ16163 Oregon 11009.130490 Yes \n", + "419 419 GW43195 Oregon 25807.063000 Yes \n", + "442 442 IP94270 Arizona 13736.132500 Yes \n", + "587 587 FJ28407 California 5619.689084 Yes \n", + "\n", + " Coverage Education Effective To Date EmploymentStatus Gender \\\n", + "189 Premium Bachelor 1/24/11 Employed F \n", + "236 Premium Bachelor 1/24/11 Employed F \n", + "419 Extended College 2/13/11 Employed F \n", + "442 Premium Master 2/13/11 Disabled F \n", + "587 Premium High School or Below 1/26/11 Unemployed M \n", + "\n", + " ... Number of Open Complaints Number of Policies Policy Type \\\n", + "189 ... 0.0 1 Corporate Auto \n", + "236 ... 0.0 1 Special Auto \n", + "419 ... 1.0 2 Personal Auto \n", + "442 ... 0.0 8 Personal Auto \n", + "587 ... 0.0 1 Personal Auto \n", + "\n", + " Policy Renew Offer Type Sales Channel Total Claim Amount \\\n", + "189 Corporate L3 Offer2 Agent 1358.400000 \n", + "236 Special L3 Offer2 Agent 1358.400000 \n", + "419 Personal L2 Offer1 Branch 1027.200000 \n", + "442 Personal L2 Offer1 Web 1261.319869 \n", + "587 Personal L1 Offer2 Web 1027.000029 \n", + "\n", + " Vehicle Class Vehicle Size Vehicle Type \n", + "189 Luxury Car Medsize NaN \n", + "236 Luxury Car Medsize A \n", + "419 Luxury Car Small A \n", + "442 SUV Medsize A \n", + "587 SUV Medsize A \n", + "\n", + "[5 rows x 26 columns]\n" + ] + } + ], + "source": [ + "# Filtrar el DataFrame para incluir solo filas que cumplan con ambas condiciones\n", + "filtered_df = df[\n", + " (df['Total Claim Amount'] > 1000) & # Asegúrate de que esta columna existe y está correcta\n", + " (df['Response'] == 'Yes') # Asegúrate de que esta columna existe y está correcta\n", + "]\n", + "\n", + "# Mostrar las primeras filas del DataFrame filtrado\n", + "print(filtered_df.head())" + ] + }, + { + "cell_type": "markdown", + "id": "b9be383e-5165-436e-80c8-57d4c757c8c3", + "metadata": { + "id": "b9be383e-5165-436e-80c8-57d4c757c8c3" + }, + "source": [ + "2. Using the original Dataframe, analyze the average total_claim_amount by each policy type and gender for customers who have responded \"Yes\" to the last marketing campaign. Write your conclusions." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "8a023f05-0f72-43e8-9afa-c69498c4d3a6", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "b42999f9-311f-481e-ae63-40a5577072c5", - "metadata": { - "id": "b42999f9-311f-481e-ae63-40a5577072c5" - }, - "source": [ - "## Bonus" - ] - }, + "name": "stdout", + "output_type": "stream", + "text": [ + "Gender F M\n", + "Policy Type \n", + "Corporate Auto 433.74 408.58\n", + "Personal Auto 452.97 457.01\n", + "Special Auto 453.28 429.53\n" + ] + } + ], + "source": [ + "\n", + "\n", + "# Supongamos que 'insurance_df' es tu DataFrame original\n", + "\n", + "# Filtrar el DataFrame para incluir solo las filas con respuesta \"Yes\"\n", + "responded_yes_df = df[df['Response'] == 'Yes']\n", + "\n", + "# Crear una tabla pivote para el promedio de 'Total Claim Amount' por 'Policy Type' y 'Gender'\n", + "pivot_table = responded_yes_df.pivot_table(\n", + " values='Total Claim Amount',\n", + " index='Policy Type',\n", + " columns='Gender',\n", + " aggfunc='mean'\n", + ").round(2) # Redondea a dos decimales para mayor claridad\n", + "\n", + "# Mostrar la tabla pivote\n", + "print(pivot_table)" + ] + }, + { + "cell_type": "markdown", + "id": "7050f4ac-53c5-4193-a3c0-8699b87196f0", + "metadata": { + "id": "7050f4ac-53c5-4193-a3c0-8699b87196f0" + }, + "source": [ + "3. Analyze the total number of customers who have policies in each state, and then filter the results to only include states where there are more than 500 customers." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "234d2a0e-b299-4591-96a8-768092b830c3", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "81ff02c5-6584-4f21-a358-b918697c6432", - "metadata": { - "id": "81ff02c5-6584-4f21-a358-b918697c6432" - }, - "source": [ - "5. The marketing team wants to analyze the number of policies sold by state and month. Present the data in a table where the months are arranged as columns and the states are arranged as rows." - ] - }, + "name": "stdout", + "output_type": "stream", + "text": [ + " State Number of Customers\n", + "0 Arizona 1937\n", + "1 California 3552\n", + "2 Nevada 993\n", + "3 Oregon 2909\n", + "4 Washington 888\n" + ] + } + ], + "source": [ + "\n", + "\n", + "# Agrupar por 'State' y contar el número de clientes por estado\n", + "state_counts = df.groupby('State').size().reset_index(name='Number of Customers')\n", + "\n", + "# Filtrar estados con más de 500 clientes\n", + "states_with_more_than_500_customers = state_counts[state_counts['Number of Customers'] > 500]\n", + "\n", + "# Mostrar los resultados\n", + "print(states_with_more_than_500_customers)" + ] + }, + { + "cell_type": "markdown", + "id": "b60a4443-a1a7-4bbf-b78e-9ccdf9895e0d", + "metadata": { + "id": "b60a4443-a1a7-4bbf-b78e-9ccdf9895e0d" + }, + "source": [ + "4. Find the maximum, minimum, and median customer lifetime value by education level and gender. Write your conclusions." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "9148dc2f-6966-4c6b-a6d6-bb5ab7f1ca89", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "b6aec097-c633-4017-a125-e77a97259cda", - "metadata": { - "id": "b6aec097-c633-4017-a125-e77a97259cda" - }, - "source": [ - "6. Display a new DataFrame that contains the number of policies sold by month, by state, for the top 3 states with the highest number of policies sold.\n", - "\n", - "*Hint:*\n", - "- *To accomplish this, you will first need to group the data by state and month, then count the number of policies sold for each group. Afterwards, you will need to sort the data by the count of policies sold in descending order.*\n", - "- *Next, you will select the top 3 states with the highest number of policies sold.*\n", - "- *Finally, you will create a new DataFrame that contains the number of policies sold by month for each of the top 3 states.*" - ] - }, + "name": "stdout", + "output_type": "stream", + "text": [ + " Education Gender max min median\n", + "0 Bachelor F 73225.95652 1904.000852 5640.505303\n", + "1 Bachelor M 67907.27050 1898.007675 5548.031892\n", + "2 College F 61850.18803 1898.683686 5623.611187\n", + "3 College M 61134.68307 1918.119700 6005.847375\n", + "4 Doctor F 44856.11397 2395.570000 5332.462694\n", + "5 Doctor M 32677.34284 2267.604038 5577.669457\n", + "6 High School or Below F 55277.44589 2144.921535 6039.553187\n", + "7 High School or Below M 83325.38119 1940.981221 6286.731006\n", + "8 Master F 51016.06704 2417.777032 5729.855012\n", + "9 Master M 50568.25912 2272.307310 5579.099207\n" + ] + } + ], + "source": [ + "\n", + "# Asegurarse de que 'Customer Lifetime Value' es numérico\n", + "df['Customer Lifetime Value'] = pd.to_numeric(df['Customer Lifetime Value'], errors='coerce')\n", + "\n", + "# Agrupar por 'Education' y 'Gender', calculando máximo, mínimo y mediana\n", + "clv_stats = df.groupby(['Education', 'Gender'])['Customer Lifetime Value'].agg(['max', 'min', 'median']).reset_index()\n", + "\n", + "# Mostrar los resultados\n", + "print(clv_stats)" + ] + }, + { + "cell_type": "markdown", + "id": "b42999f9-311f-481e-ae63-40a5577072c5", + "metadata": { + "id": "b42999f9-311f-481e-ae63-40a5577072c5" + }, + "source": [ + "## Bonus" + ] + }, + { + "cell_type": "markdown", + "id": "81ff02c5-6584-4f21-a358-b918697c6432", + "metadata": { + "id": "81ff02c5-6584-4f21-a358-b918697c6432" + }, + "source": [ + "5. The marketing team wants to analyze the number of policies sold by state and month. Present the data in a table where the months are arranged as columns and the states are arranged as rows." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "c8b817c1-1360-4fd5-bb02-2c6091da8324", + "metadata": {}, + "outputs": [ { - "cell_type": "markdown", - "id": "ba975b8a-a2cf-4fbf-9f59-ebc381767009", - "metadata": { - "id": "ba975b8a-a2cf-4fbf-9f59-ebc381767009" - }, - "source": [ - "7. The marketing team wants to analyze the effect of different marketing channels on the customer response rate.\n", - "\n", - "Hint: You can use melt to unpivot the data and create a table that shows the customer response rate (those who responded \"Yes\") by marketing channel." - ] + "name": "stdout", + "output_type": "stream", + "text": [ + "Month 1 2\n", + "State \n", + "Arizona 3052 2864\n", + "California 5673 4929\n", + "Nevada 1493 1278\n", + "Oregon 4697 3969\n", + "Washington 1358 1225\n" + ] }, { - "cell_type": "markdown", - "id": "e4378d94-48fb-4850-a802-b1bc8f427b2d", - "metadata": { - "id": "e4378d94-48fb-4850-a802-b1bc8f427b2d" - }, - "source": [ - "External Resources for Data Filtering: https://towardsdatascience.com/filtering-data-frames-in-pandas-b570b1f834b9" - ] - }, + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\Lenovo\\AppData\\Local\\Temp\\ipykernel_7120\\58261480.py:2: UserWarning: Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.\n", + " df['Effective To Date'] = pd.to_datetime(df['Effective To Date'])\n" + ] + } + ], + "source": [ + "\n", + "# Asegúrate que la columna para la fecha sea de tipo datetime\n", + "df['Effective To Date'] = pd.to_datetime(df['Effective To Date'])\n", + "\n", + "# Extraer el mes de la columna de fecha\n", + "df['Month'] = df['Effective To Date'].dt.month\n", + "\n", + "# Crear una tabla pivote para contar el número de pólizas vendidas por estado y mes\n", + "policies_sold_pivot = df.pivot_table(values='Number of Policies', index='State', columns='Month', aggfunc='sum', fill_value=0)\n", + "\n", + "# Mostrar la tabla pivote\n", + "print(policies_sold_pivot)" + ] + }, + { + "cell_type": "markdown", + "id": "b6aec097-c633-4017-a125-e77a97259cda", + "metadata": { + "id": "b6aec097-c633-4017-a125-e77a97259cda" + }, + "source": [ + "6. Display a new DataFrame that contains the number of policies sold by month, by state, for the top 3 states with the highest number of policies sold.\n", + "\n", + "*Hint:*\n", + "- *To accomplish this, you will first need to group the data by state and month, then count the number of policies sold for each group. Afterwards, you will need to sort the data by the count of policies sold in descending order.*\n", + "- *Next, you will select the top 3 states with the highest number of policies sold.*\n", + "- *Finally, you will create a new DataFrame that contains the number of policies sold by month for each of the top 3 states.*" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "f8ba850e-913e-405c-81ca-7c1c1be291cb", + "metadata": {}, + "outputs": [ { - "cell_type": "code", - "execution_count": null, - "id": "449513f4-0459-46a0-a18d-9398d974c9ad", - "metadata": { - "id": "449513f4-0459-46a0-a18d-9398d974c9ad" - }, - "outputs": [], - "source": [ - "# your code goes here" - ] + "name": "stdout", + "output_type": "stream", + "text": [ + "Month State 1 2\n", + "0 Arizona 3052 2864\n", + "1 California 5673 4929\n", + "2 Oregon 4697 3969\n" + ] } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "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.9.13" - }, - "colab": { - "provenance": [] + ], + "source": [ + "import pandas as pd\n", + "\n", + "# Supón que 'insurance_df' es tu DataFrame original y ya tiene todos los datos necesarios\n", + "\n", + "# Convertir 'Effective To Date' a formato de fecha, si no lo está ya\n", + "df['Effective To Date'] = pd.to_datetime(df['Effective To Date'])\n", + "\n", + "# Extraer el mes de la columna de fecha\n", + "df['Month'] = df['Effective To Date'].dt.month\n", + "\n", + "# Sumar el número de pólizas por estado\n", + "state_totals = df.groupby('State')['Number of Policies'].sum().reset_index()\n", + "\n", + "# Obtener los nombres de los 3 principales estados con el mayor número de pólizas vendidas\n", + "top_states = state_totals.nlargest(3, 'Number of Policies')['State']\n", + "\n", + "# Filtrar el DataFrame original para incluir solo los 3 estados principales\n", + "top_states_df = df[df['State'].isin(top_states)]\n", + "\n", + "# Crear y mostrar una tabla pivote de las pólizas vendidas por mes y estado\n", + "result_df = top_states_df.pivot_table(\n", + " values='Number of Policies',\n", + " index='State',\n", + " columns='Month',\n", + " aggfunc='sum',\n", + " fill_value=0\n", + ").reset_index()\n", + "\n", + "print(result_df)" + ] + }, + { + "cell_type": "markdown", + "id": "ba975b8a-a2cf-4fbf-9f59-ebc381767009", + "metadata": { + "id": "ba975b8a-a2cf-4fbf-9f59-ebc381767009" + }, + "source": [ + "7. The marketing team wants to analyze the effect of different marketing channels on the customer response rate.\n", + "\n", + "Hint: You can use melt to unpivot the data and create a table that shows the customer response rate (those who responded \"Yes\") by marketing channel." + ] + }, + { + "cell_type": "markdown", + "id": "e4378d94-48fb-4850-a802-b1bc8f427b2d", + "metadata": { + "id": "e4378d94-48fb-4850-a802-b1bc8f427b2d" + }, + "source": [ + "External Resources for Data Filtering: https://towardsdatascience.com/filtering-data-frames-in-pandas-b570b1f834b9" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "449513f4-0459-46a0-a18d-9398d974c9ad", + "metadata": { + "id": "449513f4-0459-46a0-a18d-9398d974c9ad" + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " Sales Channel Response Rate (%)\n", + "0 Agent 18.005339\n", + "1 Branch 10.787558\n", + "2 Call Center 10.322279\n", + "3 Web 10.885609\n" + ] } + ], + "source": [ + "\n", + "# Filtrar clientes que respondieron \"Yes\"\n", + "yes_responses = df[df['Response'] == 'Yes']\n", + "\n", + "# Calcular el total de respuestas \"Yes\" por canal de ventas\n", + "yes_counts_by_channel = yes_responses.groupby('Sales Channel').size()\n", + "\n", + "# Calcular el total de clientes por canal de ventas\n", + "total_by_channel = df.groupby('Sales Channel').size()\n", + "\n", + "# Calcular la tasa de respuesta\n", + "response_rate_by_channel = (yes_counts_by_channel / total_by_channel) * 100\n", + "\n", + "# Convertir a DataFrame para mejor legibilidad\n", + "response_rate_df = response_rate_by_channel.reset_index(name='Response Rate (%)')\n", + "\n", + "# Mostrar la tabla de resumen\n", + "print(response_rate_df)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "10c9c861-e704-495f-96b1-c18c40be933b", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" }, - "nbformat": 4, - "nbformat_minor": 5 -} \ No newline at end of file + "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.12.7" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}