<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alan Paz Ribeiro on Medium]]></title>
        <description><![CDATA[Stories by Alan Paz Ribeiro on Medium]]></description>
        <link>https://medium.com/@alanjpr?source=rss-2c8ee671d68a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jecc5YzhmFiQ9EH9_o-ySA.jpeg</url>
            <title>Stories by Alan Paz Ribeiro on Medium</title>
            <link>https://medium.com/@alanjpr?source=rss-2c8ee671d68a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:19:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alanjpr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Web Scraping com BeautifulSoup e Python]]></title>
            <link>https://medium.com/@alanjpr/web-scraping-com-beautifulsoup-e-python-174015c863e2?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/174015c863e2</guid>
            <category><![CDATA[python-beautifulsoup4]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[e-commerce-business]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 14:51:31 GMT</pubDate>
            <atom:updated>2024-03-04T14:51:31.586Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extraindo dados da web do Mercado Livre para análise</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZoPblSnQQRXRr0bFLBunpg.jpeg" /></figure><h3>Introdução</h3><p>Web scraping, também conhecido como extração de dados da web, é um método essencial em diversas áreas, como análise de dados, business intelligence, pesquisa de mercado e comércio eletrônico. Essa técnica envolve a coleta e conversão de dados online, incluindo preços de produtos, artigos de notícias, postagens em mídias sociais, informações de contato e dados financeiros, em formatos úteis.</p><p>Envolve o envio de solicitações HTTP a um site para obter HTML ou outros dados estruturados, posteriormente analisados e usados para recuperar as informações precisas que você precisa das páginas da Web. Esses dados podem estar na forma de links, textos, imagens, etc.</p><p>Em um mundo cada vez mais orientado por dados, o processo de web scraping combina e organiza informações em escala, permitindo que os tomadores de decisão obtenham conhecimento perspicaz, monitorem tendências e façam escolhas sábias. No entanto, a natureza dinâmica das informações da web, a necessidade de metodologias de raspagem confiáveis e flexíveis e as questões éticas e legais (Dilmegani, 2023) fornecem desafios para a extração de dados da web. Esta investigação inicial estabelecerá as bases para a utilização responsável e bem-sucedida da extração de dados da web.</p><h3><strong>Web Scraping com Python</strong></h3><p>Web scraping pode ser realizado com a ajuda de ferramentas ou bibliotecas Python. Neste artigo, vamos nos concentrar em usar bibliotecas Python para obter nosso conteúdo desejado de um site. Usaremos a biblioteca BeautifulSoup para realizar web scraping porque:</p><p><strong>Beautiful Soup</strong> é uma biblioteca Python projetada para analisar documentos HTML e XML. Ele é utilizado para extrair dados da estrutura HTML de páginas web. O Beautiful Soup pode navegar pelo documento HTML, identificando elementos específicos, como qualquer tag HTML com uma determinada classe ou ID e, em seguida, extraindo as informações desejadas.</p><h3><strong>O Mercado Livre</strong></h3><p>Foi escolhido o ramo do e-commerce para aplicar a técnica de Web scraping e, dentro desse ramo, o site do Mercado Livre foi escolhido por ser líder de market share do e-commerce no Brasil e também por ser muito popular entre os consumidores.</p><h3>1 Início</h3><h4>1.1 Importando as bibliotecas</h4><p>Serão importadas as bibliotecas pandas, requests, datetime e BeautifulSoup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*ll_dYuWKbgaYmiNDInvR5Q.png" /></figure><p>Nosso objetivo é verificar as principais ofertas do dia no site. Então a referência de início será a página principal do Mercado Livre contendo essas informações</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*nvDxXOMHRMZKzhe34Zy_bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*atoMYvR0kR-s6Rc-oWErTg.png" /></figure><p>A chave para uma web scraping eficaz é entender a estrutura da página da Web de referência e encontrar a informação de que precisa em suas respectivas tags <strong><em>&lt;tag&gt;</em></strong></p><p>Após identificar no site a tag respectiva correspondente ao nome do produto, essa informação é extraída conforme abaixo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*XMUSqp0F8nlteMAZEwupUQ.png" /></figure><p>O mesmo procedimento é feito para a informação dos preços dos produtos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*8Y2TcCI67uIg1bKenkyPcQ.png" /></figure><p>Como estamos fazendo uma requisição de informações em um site, é preciso monitorar a resposta do mesmo para que o processo não tenha falhas. Esse processo de requests é monitorado conforme abaixo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*hHBqE2ypfL6eQ22x5yILNQ.png" /></figure><p>Feito isso, agora é agrupar todas as informações em um dataframe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*_ZIL2vASHqRbN65K0mq-cA.png" /></figure><p>Atribuindo à variável a quantidade de páginas a serem realizadas as extrações, convertendo a coluna datetime e retirando os caracteres especiais aplicando <em>regex</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*CMjy6FTFtO4lWUid13k6Eg.png" /></figure><p>Tem-se o dataframe com as informações dos produtos em oferta no dia bem como seus respectivos preços</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ocpeN51kO9_7WB0YPdcKwQ.png" /></figure><p>Se você tem dívidas ou sugestões do projeto, não hesite em me contactar!</p><p>Muito obrigado pela leitura</p><p>Conexões:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174015c863e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Otimizando as Despesas do Marketing aplicando Python e Machine Learning]]></title>
            <link>https://medium.com/@alanjpr/otimizando-as-despesas-do-marketing-aplicando-python-e-machine-learning-704e7448f9e8?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/704e7448f9e8</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[cohorts]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 01:01:36 GMT</pubDate>
            <atom:updated>2024-02-29T01:01:36.577Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uma abordagem passo a passo em Python para prever o sucesso de uma campanha de marketing analisando o comportamento dos usuários em um site por origem de visita</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ov-y1--MDdyXJj2_L8HJGQ.jpeg" /></figure><h4><strong>Objetivo e Etapas do Projeto</strong></h4><p>Faça relatórios e calcule as métricas:</p><p>1- Produto<br> — Quantas pessoas usam-no cada dia, semana e mês?<br> — Quantas sessões ocorrem por dia? (um usuário pode realizar várias sessões).<br> — Que comprimento tem cada sessão?<br> — Com que frequência os usuários voltam?</p><p>2- Vendas<br> — Quando as pessoas começam a comprar? (Na análise de KPIs, nós geralmente estamos interessados em saber o período de tempo entre o registro e a conversão — quando o usuário se torna um cliente. Por exemplo, se o registro e a primeira compra de um usuário ocorrem no mesmo dia, ele pode encaixar na categoria de Conversão 0d. Se a compra é realizada no dia seguinte, isso será a Conversão 1d. Você pode usar qualquer abordagem que permita comparar as conversões de diferentes coortes, para que você possa determinar qual coorte ou canal de marketing tem a maior eficiência)<br> — Quantos pedidos os clientes fazem durante um determinado período de tempo?<br> — Qual é o volume médio de uma compra?<br> — Quanto dinheiro eles trazem para a empresa (LTV)?</p><p>3- Marketing<br> — Quanto dinheiro foi gasto? No total/por origem/ao longo do tempo<br> — Quanto custou a aquisição de clientes para cada origem?<br> — Os investimentos valeram a pena? (ROI)</p><p>Construa gráficos para ver como essas métricas diferem para vários dispositivos e diferentes origens de anúncios e como elas mudam com o tempo.</p><p><strong><em>Escreva uma conclusão: recomende aos especialistas de marketing quanto dinheiro e onde seria melhor investir.</em></strong></p><p><strong><em>Quais origens/plataformas você recomendaria? Fundamente sua escolha: em quais métricas você se concentrou? Por quê? Que conclusões você tirou ao encontrar os valores das métricas?</em></strong></p><h3>O Dataset</h3><p>O conjunto de dados é disponibilizado em formato de arquivo <strong><em>.CSV</em></strong> (<a href="https://github.com/alanpazribeiro/Otimizando-Despesas-com-Marketing/blob/main/costs_us.csv"><em>costs_us.csv</em></a><em>, </em><a href="https://github.com/alanpazribeiro/Otimizando-Despesas-com-Marketing/blob/main/orders_log_us.csv"><em>orders_log.csv </em></a>e<em> </em><a href="https://github.com/alanpazribeiro/Otimizando-Despesas-com-Marketing/blob/main/visits_log_us.csv"><em>visits_log.csv</em></a><em>) </em>com 360.000 linhas de dados.</p><p>O dataset inclui os seguintes campos:</p><p>1- A tabela <em>visits </em>(os logs do servidor com dados sobre os visits ao site):<br> — <strong>Uid —</strong> identificador unívoco do usuário<br> <strong>— Device —</strong> dispositivo do usuário<br><strong> — Start Ts</strong> — data e hora do início da sessão<br><strong> — End Ts </strong>— data e hora do final da sessão<br><strong> — Source Id </strong>— identificador da origem do anúncio através do qual o usuário chegou<br><em> — Todas as datas nesta tabela estão no formato YYYY-MM-DD.</em><br>2- A tabela <em>orders </em>(dados sobre os pedidos):<br><strong> — Uid</strong> — identificador unívoco do usuário que faz um pedido<br> <strong>— Buy Ts </strong>— data e hora do pedido<br><strong> — Revenue</strong> — a receita da Y.Afisha com o pedido<br>3- A tabela <em>costs </em>(dados sobre as despesas com marketing):<br> <strong>— source_id </strong>— identificador da origem de anúncio<br><strong> — dt </strong>— data<br><strong> — costs</strong> — despesas com esta origem de anúncio neste dia</p><h3>1 — Início</h3><h4>1 .1 — Importando bibliotecas e conjunto de dados</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*OmSZA3OzQY0IbV6n9pky1Q.png" /></figure><h4>1.2 Carregando bases de dados</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*BdpA0m5671bI5ycJUkHmpg.png" /></figure><h3>2 Explorando os dados</h3><h4>2.1 Informações gerais / resumidas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*n5cinarsuhrNiqwPA2QvFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*HHqAs-RTzdz5-t8X3qCpyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gINYLM0E0UioT0L4U1i0hA.png" /></figure><p>Informações gerais dos datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*xwdoAfDlkJUHJuV-ZM-xZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*nx1xcbpR9BL66dq958jpEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*2f0mU9n2K1S3ZlZiwGC08Q.png" /></figure><p>Descrição geral dos datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*ebevHzRZw5TCS0q1fjmHTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WLkMQkKl5hVEAnUTyPz_Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*FGSU2lCpjuISU9l6Id0lfQ.png" /></figure><p>Verificando valores ausentes nos datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*xXQCa4KV-zKMNxd_HeV1uQ.png" /></figure><p>Verificando valores duplicados nos datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*iChhNvGd5I0T26H3vo8t1A.png" /></figure><p>Pelas informações detalhadas dos arquivos ‘visits’,’orders’ e ‘costs’, percebe-se a consistência dos dados, pois não há valores duplicados, não há valores nulos ou ausentes. Nas colunas onde há informações de data nos conjuntos de dados, será feito a alteração do tipo de dado, pois está como tipo ‘object’. Será feito alterações nos nomes das colunas para mater o padrão de boas práticas.</p><h4>2.2 Corrigindo os dados</h4><h4>2.2.1 Alterando o tipo de dado das colunas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*XRNMwyzSbd1niTWfCNpwUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*22QPUGlqqUs8UVJKxhTOyw.png" /></figure><p>Corrigindo o tipo de dado da coluna <em>‘buy_Ts’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*XA_yOUnhKfXohKxmhUW_sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*HIVPCUenRpiVFQt8nItIOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*5eicI8tF_MSEWbwYv4CoQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*yUqWP-JrO6AfE1SM6clYRA.png" /></figure><p>Verificando os conjuntos de dados aplicando o método<em> .decribe()</em>, nota-se que há simetria nas datas de início (2017–06–01) e fim (2018–06–01) dos três datasets.</p><h4>2.2.2 Renomeando e reorganizando as colunas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*3kDOcPlvJbhhy1_TT8B7Iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*r44FgWkFer5KtocAVlwUSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*TltaHEGRAy_8a4oDMHHkgw.png" /></figure><h3>3 Métricas dos Usuários</h3><h4>3.1 Produto</h4><h4>3.1.1 Utilização diária, dia da semana e mensal</h4><p>Para verificar a popularidade e sucesso da plataforma, é necessário avaliar as atividades diária, dia da semana e mensal dos usuários. Para isso, há três métricas principais que descrevem esse comportamento:</p><ul><li>DAU — número de usuários unívocos ativos por dia</li><li>WAU — número de usuários unívocos ativos por dia da semana</li><li>MAU — número de usuários unívocos ativos mensal</li></ul><p>Para isso será criado as colunas <em>‘visits_date’, ‘visits_week’ </em>e<em> ‘visits_month’</em> separando as respectivas informações da coluna <em>‘start_ts’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*JbqKT-ebQimW9Fv17x1YQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*eDJmxI9bSlmS0PUzvtIIeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*9qLj_qCaUvp_xMSgf_5QpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*cP-YIHZrizYImjbvNmGRgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*lhJJQDH64hl1MNiBlpQaeg.png" /></figure><p>Gráfico do Volume de Acessos Diário</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Go51yO4JRUd_wO8X8xztqQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*g0Bo4BtVA9fbKo3lB2ONZg.png" /></figure><p>Gráfico Volume de Acessos Diário por dia da semana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*ulE7gcKSpllr7gnIaYBhtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*WtjR5Kz9DvlSon87r-ZNIg.png" /></figure><p>Gráfico do Volume de Acessos Semanais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*qbTqJL2wBYcJx80OkOMNew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qAf8ly1iukxibOPclabKoA.png" /></figure><p>Gráfico do Volume de Acessos Mensais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*HlamXQqjVzHvBzzs4el73Q.png" /></figure><p>Cálculo das taxas de retenção semanal e mensal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*DC98xcCrhIYtmbWd0jGx5Q.png" /></figure><p>Pelos gráficos plotados das tabelas geradas por visitas diárias, semanais e mensais no período de 1 ano, é possível verificar que:</p><ul><li>no gráfico diário, nota-se pequenos picos positivos e negativos a longo do gráfico; do mês 6 até o final do ano o comportamento é de maneira ascendente e janeiro o comportamento se inverte, mas permanecendo os pequenos picos. Ao plotar a tabela diária com os nomes dos dias verifica-se um certo padrão em relação aos pequenos picos e vales visto no gráfico.</li><li>O gráfico “Volume e Acessos diários por dia da Semana” demonstra melhor esse comportamento sazonal, onde as linhas nas cores laranja, azul e amarela (sexta, segunda e quinta respectivamente) são os dias com maior acesso, diferente dos finais de semana (roxo-sábado e cinza-domingo) onde as linhas estão abaixo das demais no gráfico.</li><li>já no gráfico semanal, é possível verificar melhor o comportamento linear negativo, com a queda se iniciando na semana 22 tendo seu ponto mínimo a semana 31, tendo um aumento na semana 28 (junho a agosto)</li><li>no gráfico mensal, verifica-se o comportamento mês a mês do produto/serviço oferecido, com uma ascensão enorme a partir de agosto indo até novembro, onde é possível constatar a preferência dos usuários nesse período. Nos demais meses há uma queda acentuada, com poucos picos ao longo do período, o que demostra que o produto/serviço é de um nicho bem específico tendo sua maior procura em um determinado período do ano.</li><li>foi calculado os valores das atividades diárias <strong>(DAU)</strong>, semanal <strong><em>(WAU)</em></strong> e mensal <strong><em>(MAU)</em></strong> dos usuários. Após isso foi calculado a taxa de retorno semanal<em>(taxa_wau)</em> chegando em um valor de 100%, ou seja, das pessoas que visitam a plataforma em média 100% delas retornam em uma semana a visitar a plataforma. Já para o cálculo da taxa de retorno mensal<em>(taxa_mau)</em> esse valor é de 3.9%.</li></ul><h4>3.1.2 Sessões dos usuários</h4><p>A sessão do usuário é medida do momento da entrada na plataforma até o fechamento da mesma. Como o mesmo usuário pode entrar várias vezes, será calculado o valor único para cada usuário.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*auOBW8so1q18H4sLNshSgQ.png" /></figure><p>Agrupando acessos semanais e mensais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*n6tqtx-WwrUGrZqB6_oR-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*otjfzyqyY6pIwTUnentnSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*SBuWt2fof3jb_qo3qFhHsA.png" /></figure><p>Pelos filtros realizados nas tabelas, verifica-se que pouco mais de uma sessão por usuário por semana na plataforma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*rOM7XrhVLVZ_ezxM-OwmaA.png" /></figure><p>Agrupando os acessos diários</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*-60L53Fr-0VB7edLz6YZWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*D0Jq6oHfobPQ9fxTWGd0kA.png" /></figure><p>Calculando a média</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*21qtABl2RLtG2lW2bY_qGQ.png" /></figure><p>Gráficos de Acessos Diários de Usuários Únicos e Totais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*qMYhb3u8fRsm3Dupj0UPyA.png" /></figure><p>Pelos gráficos semanais e diários acima plotados onde é possível notar um comportamento semelhante entre os usuários que acessam a plataforma pela primeira vez e aqueles que acessam mais de uma vez, seja o acesso computado diário ou semanalmente.</p><h4>3.1.3 Duração das sessões</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Ek-c-tG3MwL6B2Cfe1JmJw.png" /></figure><p>Duração das sessões</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*tZO3edAiChWQ1V3LBvamgA.png" /></figure><p>Cálculo da média</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*YtBXRynpcl9tmI8ho0FpiQ.png" /></figure><p>Cálculo da mediana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*hRta86kQrPdbm42TkcUQZw.png" /></figure><p>Gráfico tipo histograma das Durações dos Acessos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*6IQJu4Ig0PzLbTcffFl0Nw.png" /></figure><p>Pelo histograma acima plotado da “Duração(s) das visitas semanais”, percebe-se a variabilidade dos dados. Acima também foram geradas as tabelas de Media da duração(s) das visitas semanais, Mediana da duração(s) das visitas semanais e Moda da duração(s) das visitas semanais, onde verifica-se um range grande nos valores, mesmo nas médias e medianas. Como a moda é uma medida de tendência central e destaca o elemento com maior frequência em um conjunto de dados, pode-se utilizá-la para determinar o tempo médio de duração das sessões.</p><h4>3.2 Calculando Taxa de Retenção e Índice de Cancelamento</h4><p>Para verificar a popularidade e assiduidade dos usuários em um aplicativo ou plataforma, é necessário calcular o Índice de Retenção e a Taxa de Cancelamento. Índice de Retenção fornece uma informação importante que é a quantidade de usuários de uma determinada cohort que permanecem ativos comparado com a quantidade inicial.</p><h4>3.2.1 Taxa de Retenção</h4><p>Criando uma coluna com a data do primeiro acesso</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*srGSjdiOTK1NELk4UlN1rA.png" /></figure><p>Como verificou-se acima uma variação grande na quantidade de acessos dos usuários, serão criadas cohorts semanais com o intuito de obter uma melhor precisão nos dados e na análise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yD3Pyu0zgCosLjry5sMbnQ.png" /></figure><p>Calculando a diferença entre as datas semanais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Yrwk36uWuRfYBO2njyO1Jw.png" /></figure><p>Calculando a diferença entre o primeiro acesso e os acessos semanais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*DXz82EYlqkXRJAkp_JuWjQ.png" /></figure><p>Criando a Cohort semanal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*cmu45DUcgJMJSl61_-NHXQ.png" /></figure><p>Agrupando, criando as Cohorts e calculando o índice dos acessos semanais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*7T-sN7tkQp99iy5QtsbtwQ.png" /></figure><p>Agrupando por Cohort</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*P5zS5WJTgXhtvP74MaU6TQ.png" /></figure><p>Selecionando a data e calculando a média da Cohort</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*DLNljbWrK0DHAZoIQ_IZFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*P6xo8O0bBZe4Fz8xdvjB1w.png" /></figure><p>Gráfico da Taxa de Retenção</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*NhBS6Vatj63xkTtWnpPlsg.png" /></figure><p>Pelas tabelas e gráficos plotados acima, percebe-se o comportamento da taxa de retenção se usuários na plataforma ao longo do período. Os pontos mais críticos que demandam atenção são os meses de agosto, dezembro e março, onde a curva atinge seus valores mínimos. Já o melhor período de retenção dos usuários é no mês de novembro.</p><h4>3.2.2 Índice de Cancelamento</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*3iY78dnBQcopifkNyxp3EQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*A5y5fBLDL423wEnoTagwlg.png" /></figure><p>Selecionando a data e calculando a média</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Xki_9N-v0VGO15o-v8zLDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*gx7omsTLmrIzNlCWaxAwrA.png" /></figure><p>Gráfico do Índice de Cancelamento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*PP4Z2b8VkU0DKSP_zPGiGQ.png" /></figure><p>Como já esperado, as tabelas e gráficos plotados tem o comportamento igual ao gráfico da taxa de retenção, com pontos de mínimos e máximos exatamente iguais.</p><p>Verificando a data da primeira compra dos usuários e variação entre os meses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*tTaZj-gyDuN8htc-56kn8w.png" /></figure><p>Renomeando as colunas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ltbmokhvvILtcnceEt1z5g.png" /></figure><p>Verificando as vendas mensais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*CdfJwzCY8t4Iu6p5nKZd-g.png" /></figure><p>Gráfico da Receita e Volume de Acessos Mensais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*2SztlrA2phUbLV1DfvD8nA.png" /></figure><p>Pelo gráfico plotado acima entre quantidade de acessos e quantidade de vendas mensais ao longo do período, nota-se um comportamento proporcional entre as linhas, ou seja, quando há aumento dos acessos também há aumento das vendas. Interessante notar alguns períodos específicos onde esse comportamento não é seguido: no mês de junho/17 e fevereiro/18 percebe-se um aumento nos acessos e uma leve quedas nas vendas. um ponto interessante é no mês de dezembro onde todos os acessos foram convertidos em vendas, ou seja, é possível dizer que todas os usuários que acessaram em dezembro fizeram pelo menos uma compra.</p><h4>3.3 Vendas mensais, origem das vendas e dispositivos</h4><p>Será analisado agora as vendas mensais por origem de anúncio <strong>(‘source_id’)</strong> e dispositivo utilizado pelo usuário para acesso à plataforma <strong><em>(‘device’)</em></strong>. Será feito um agrupamento de algumas colunas entre as tabelas ‘orders’ e a tabela ‘visits’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*THECEGyCTzP5RiMAEyFubg.png" /></figure><p>Adicionando a informação da coluna<strong><em> ‘device’</em></strong> no dataset<strong><em> ‘orders’</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*uyG1XHSebnWB9TH8zfw-eg.png" /></figure><p>Verificando os valores nulos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*2FYQAgEM9Xyt7oTmpVzExw.png" /></figure><p>Verificando a consistência dos dados por uma fatia do conjunto total</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*zNlpod52DUBVl9bhHXh1SQ.png" /></figure><p>Foi adotado o método ‘merge how=’left’ para agregar à tabela ‘orders’(50415 linhas) as informações ‘device’ e <strong><em>‘source_id’</em></strong>. No entanto, pelo verificado acima, a tabela <strong><em>‘orders_date’ </em></strong>ficou com 56772 linhas e 8655 linhas com valores nulos. Pela verificação feita acima nota-se a inconsistência da tabela ‘orders’ pois para o mesmo <strong><em>‘uid’</em></strong> (3738863118490040629) há 3 registros na tabela ‘orders’ porém somente consta 2 registros na tabela ‘visits’ (impossível alguém fazer uma compra em uma plataforma sem que, para isso, tenha visitado o site para tal). Portanto, optou-se por outra abordagem: será adotado o método ‘merge how=inner’, para que se tenha certeza de há registro de uma compra do usuário bem como de sua visita à plataforma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*lkOzxYsmzxdka_Z_32t8gw.png" /></figure><p>Verificando a consistência dos dados por uma fatia do conjunto total</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*wbSUG9wh8CxwQIEn2RDcpw.png" /></figure><p>Com isso, é possível assegurar a consistência dos dados entre as tabelas ‘orders’ e ‘visits’, ou seja, há o registro da compra e também o registro da visita. Houve uma perda no volume de dados da tabela ‘orders’ em cerca de 5% (de 50400 linhas para 48100). Porém, devido baixa quantidade, não haverá um grande impacto na análise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*LqCZx40muFuoMQTg5n-97w.png" /></figure><p>Gráfico dos Acessos por tipo de Dispositivo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*mNmluO2y4kQd6RkEjhLzYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*jZyhFASIXEncYVTnxZhxig.png" /></figure><p>Gráfico de Acesso por tipo de fonte</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*fRNUQ4h0sTa1RsFV1s850g.png" /></figure><p>Pelas tabelas e gráficos plotados é possível verificar o comportamento dos usuários:</p><ul><li>no gráfico Acessos Mensais por dispositivo, nota-se a preferência quase unânime dos usuários em acessar a plataforma por desktop. Nem mesmo no mês de dezembro, onde é identificado o maior volume de acessos e compras, quase 80% do total desse mês veio dos acessos por desktop.</li><li>já no gráfico Acessos Mensais por Fonte a Fonte 4 ficou acima das demais em 7 dos 12 meses verificados;</li><li>a Fonte 6 não aparece listada</li><li>nos meses de junho e julho há uma queda acentuada em todas as fontes, deixando-as próximas em acessos;</li><li>as Fontes 9 e 10 são as que possuem a menor quantidade de acessos em todo o período</li></ul><p>É necessária uma melhor investigação dos motivos pelos quais os usuários estão optando mais pelo acesso via desktop, se são problemas no aplicativo móvel, problemas no site (site está adaptado para telas pequenas, meio de pagamento funcionando, etc), pois o acesso por aplicativos móveis não estão performando de forma adequada.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*bNE1uvE_vZbRFJw8sJSrww.png" /></figure><p>Agrupando pela data da primeira compra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*x0-tMWEY8pcwhp6k3i5Byg.png" /></figure><p>Usuários com compras únicas mensais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*BAz9-M6Z_Z9FcolMwwsazw.png" /></figure><p>Usuários com compras totais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Blrmb5L65NbGZj2nHc1tEw.png" /></figure><p>Gráfico de Compras de Usuários Únicos e Usuários Totais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*bciZOnzQdtHqCHTum9Zz2A.png" /></figure><p>Analisando as tabelas e gráfico plotado acima, verifica-se o comportamento dos usuários em relação ao período. Os usuários únicos (aqueles que fizeram uma única compra) está abaixo da linha azul (todas as compras dos usuários), demostrando que parte dos acessos provém de antigos clientes que fazem mais de uma compra no mês. Significa também que o produto/serviço está com dificuldades de atrair novos clientes.</p><p>Verificando a primeira compra de cada usuário de acordo com o acesso, ou seja, quanto tempo leva, em média, para um cliente fazer sua primeira compra após seu primeiro acesso</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dGqxFF0PSLMbgi2Fjlfh9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*tf_ptRuvqq9SD38D_qN4bg.png" /></figure><p>Gráfico dos Dias entre a data do primeiro acesso e a data da primeira compra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*pMTr5ZE6hSRv6Q-nK_R2fQ.png" /></figure><p>Em média um novo usuário demora 16 dias entre o seu primeiro acesso à plataforma e sua primeira compra.</p><h3>4 Construção e Análise das Cohorts</h3><h4>4.1 Cohort de LTV e CAC</h4><p>Agrupando pela primeira compra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*5V86tPFflLiXZu9zayhquA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*CvEjMheKvEuh6DPLbGZSCQ.png" /></figure><p>Quantidade de compras</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wzgkr92UmZu0DidsO1n0rA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*jYVMco_3UZg_phuhDa2Ksg.png" /></figure><p>Agrupando e somando os pedidos da primeira compra e mês de compra</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*jexWW3xfImuQFS8BrH_sGQ.png" /></figure><p>Acrescentando os dados das primeiras compras dos usuários</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2enshkW8zNxZ0Wj3bZbGmg.png" /></figure><p>Calculando Gross Profit (gp) — adotando como margem de lucro-50%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*6xH2F0MV8UmPFkvuTyJp9g.png" /></figure><p>Calculando a idade da Cohort</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*zE__840C8i-ExthODdNRuQ.png" /></figure><p>Calculando o LTV (Lifetime Value)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*nYuMmLXgTsnL8Y9c3jl70g.png" /></figure><p>Agrupando pelos valores de LTV</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*sWcqXPnnhAgYkmS9C0ok5w.png" /></figure><p>Valor da primeira Cohort (mais completa)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*VOujYYnySS4Fdy3AeO4nSg.png" /></figure><p>Em média cada usuário gerou uma receita de $10.2</p><p>Heatmap da Cohort de Retenção dos Usuários</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*xatfe1uoDCQfHJt40ohuCw.png" /></figure><p>Conforme tabelas e heatmap gerados acima, nota-se o comportamento de quanto os usuários gastaram na plataforma no período. Percebe-se um outlier no mês 9 que necessita de verificação.</p><h4>4.2 Cohort do Volume médio de compras</h4><p>Agora será analisado como a receita média de compras por usuário varia ao longo do tempo. Isso é uma métrica importante pois auxilia a entender o quanto a receita média está variando no período.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*08sN4QT6lWYe_6RMLI31gQ.png" /></figure><p>Calculando a receita por usuário</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*mUhxOHAekHBLUMGVG7OLSA.png" /></figure><p>Criando uma pivot table da média de receita por usuário</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*UuFFYx_6kj-ljbdVw3dTvw.png" /></figure><p>Criando as Cohorts dos meses</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Pf98EldpncOemD7LZyj1Mw.png" /></figure><p>Ajustando os valores das Cohorts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*pmWbp68TXmZmJg8-yKalZg.png" /></figure><p>Convertendo a coluna de data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*CQOz8MrzEgk8tZtz3fbuQg.png" /></figure><p>Gerando uma pivot table da receita</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*sHGYI_Jq8i9jO-OG9CGvvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*KeCPp234aNauZaIQ1mh4Lg.png" /></figure><p>Heatmap do Volume Médio de Compra dos Clientes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dQg9jfYhWHxhgsF5Lj4cKA.png" /></figure><p>Analisando as tabelas e heatmap plotados acima, percebe-se que o mês 06–2017 se destaca das demais cohorts om valores acima das demais. Outros destaques são as datas de 09–2017 que apresenta um valor bem atípico (já verificado na análise anterior) e a data de 12–2017 onde apresenta as duas primeiras cohorts com valores mais altos que as demais.</p><h4>4.3 Marketing</h4><p>Criando uma nova coluna</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*isvntvWQ98r602_wYfl1tw.png" /></figure><p>Verificando a Cohort necessária</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*U8QL7Pk2PSeJ-vto9te38A.png" /></figure><p>Calculando os custos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*NdBBLFau8XKkQGZzdbHASg.png" /></figure><p>Calculando o CAC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*GNGfxRKWvmnjp7rtc67VQQ.png" /></figure><p>Cada cliente custou cerca de $7.65 em investimentos em marketing.</p><p>Calculando as despesas totais</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*cUA3CiKARFsKx7L0UWgAkg.png" /></figure><p>Gráfico dos Custos Mensais no Período</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*yDNVqvD8XrDqo38gK5sbzA.png" /></figure><p>Analisando o gráfico dos Custos Mensais com Marketing ao longo do período, percebe-se um certo desequilíbrio e descasamento em relação aos acessos e compras mensais realizados pelos usuários.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*YsbvZM1VXzn6xx9Ymo2_WA.png" /></figure><p>Calculando as despesas mensais por origem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*2-KaHxiPGb4cJ3Whu_uT7A.png" /></figure><p>Gráfico dos Custos Totais por Origem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*n5-H3ertN5n0AQHshcUO_A.png" /></figure><p>Pelo gráfico acima, nota-se a a distribuição dos custos por cada fonte no período JUN/17 a MAI/18. Percebe-se a fonte 3 foi responsável por cerca de 43% de todo custo total. Em segundo e terceiro ficaram as fontes 4 e 5, com cerca de 18,5% e 15,7% respectivamente. Já as fontes 9 e 10 são as que menos receberam investimentos com cerca de 1% cada em relação ao valor total do período. As fontes 6, 7 e 8 não receberam investimentos.</p><p>Calculando o ROMI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*ss5tfzMJm2F-lkfAnEG50A.png" /></figure><p>Ajustando os valores</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*W9kI332THaacOlanVKi7zg.png" /></figure><p>Soma Acumulada</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*mwcJwuS53dVdrw7cGp3fqw.png" /></figure><p>Heatmap do Volume Médio de Compra dos Clientes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*NMm0G-inGe3JcwLnhPdSTw.png" /></figure><p>A cohort do mês 06–2017 demonstra que os investimentos em marketing foram pagos a partir do 6º mês. A cohort do mês 09–2017 continua se destacando com seus valores atípicos. Em média, as cohorts pagam seus investimentos entre 7 e 8 meses.</p><h3>5 Conclusão</h3><p>O propósito da análise é ajuda a empresa a otimizar suas despesas com o marketing, verificando as fontes de visitas e dispositivos mais adequados ao público pretendido.</p><p>No capitulo 1 foi carregado as bases de dados e bibliotecas que seriam utilizadas na análise.</p><p>No capítulo 2 foi verificado nos conjuntos de dados:</p><ul><li>os valores ausentes e duplicados</li><li>alteração nos nomes das colunas</li><li>correção do tipo de dado (principalmente datetime das bases de dados)</li><li>renomeação e reorganização das colunas em todas as bases</li></ul><p>A análise dos conjuntos de dados se dá no capítulo 3, começando pelo conjunto de dados ‘visits’ cujo objetivo é verificar a popularidade e sucesso da plataforma, sendo necessário avaliar as atividades diária, dia da semana e mensal dos usuários. Para isso, há três métricas principais que descrevem esse comportamento:</p><ul><li>DAU — número de usuários unívocos ativos diário</li><li>WAU — número de usuários unívocos ativos por dia da semana</li><li>MAU — número de usuários unívocos ativos mensais</li></ul><p>Foram plotados os respectivos gráficos de cada métrica levantada, sendo possível verificar a sazonalidade do produto/serviço oferecido ao longo do período.</p><p>Também foi calculado as sessões dos usuários no período, ou seja, quantos acessos únicos a plataforma teve no período. Para isso, fi feito um filtro dos usuários únicos (pois o mesmo usuário pode acessar a plataforma diversas vezes), chegando ao valor de 1,16 (pouco mais de 1 acesso/usuário). Foi calculado a duração das sessões dos usuários, chegando a um valor médio de 1 minuto. Isso mostra que a interação com a plataforma é baixa, principalmente quando se trata de novos usuários, que não conhecem a plataforma.</p><p>Foi calculado a data da primeira venda no conjunto de dados ‘orders’, bem como plotado um gráfico de Receitas e volume de acessos mensais afim de verificar a relação entre acessos e receita, onde verificou-se a simetria entre os gráficos, ou seja, quando há aumento dos acessos também há aumento das vendas. Interessante notar alguns períodos específicos onde esse comportamento não é seguido: no mês de junho/17 e fevereiro/18 percebe-se um aumento nos acessos e uma leve quedas nas vendas. Um ponto interessante é no mês de dezembro onde todos os acessos foram convertidos em vendas.</p><p>Também foi verificado a taxa de retenção e índice de cancelamento dos usuários na plataforma onde percebe-se o comportamento dos usuários na plataforma ao longo do período. Os pontos mais críticos que demandam atenção são os meses de agosto, dezembro e março, onde a curva atinge seus valores mínimos. Já o melhor período de retenção dos usuários é no mês de novembro. Para todo o período tem-se uma taxa de retenção média de 3,92% e índice de cancelamento de 96,08%</p><p>O objetivo no tópico “Vendas mensais, origem das vendas e dispositivos” foi a análise das vendas mensais por origem de anúncio (‘sorce_id’) e quais dispositivos eram mais utilizados pelos usuários para acesso à plataforma. Conforme descrito no tópico em questão, foi constatado inconsistência no conjunto de dados ‘orders’ (haviam registros na mesma que não constavam do conjunto de dados ‘visits’, ou seja, impossível um usuário realizar uma compra sem acessar a plataforma). Diante da inconsistência, adotou-se outro método (how=’inner’) para garantir que as informações estivessem em ambos os conjuntos de dados. Com isso, houve uma perda de 5% n volume de dados do conjunto ‘orders’, não havendo grande impacto na análise.</p><p>Com o conjunto de dados consistente, foi plotado o gráfico “Acessos Mensais por Dispositivo” e “Acessos Mensais por Fonte”, onde temos algumas observações:</p><ul><li>no gráfico Acessos Mensais por dispositivo, nota-se a preferência quase unânime dos usuários em acessar a plataforma por desktop. Nem mesmo no mês de dezembro, onde é identificado o maior volume de acessos e compras, quase 80% do total desse mês veio dos acessos por desktop.</li><li>já no gráfico Acessos Mensais por Fonte a Fonte 4 ficou acima das demais em 7 dos 12 meses verificados; a Fonte 6 não aparece listada; nos meses de junho e julho há uma queda acentuada em todas as fontes, deixando-as próximas em acessos; as Fontes 9 e 10 são as que possuem a menor quantidade de acessos em todo o período.</li></ul><p>Pelas análises e observações acima, faz-se necessário uma melhor investigação dos motivos pelos quais os usuários estão optando por acessos via desktop. Com relação às Fontes, uma análise em relação a viabilidade de algumas delas seria propício, pois percebe-se uma baixa performance de algumas.</p><p>Um fato interessante durante a análise foi verificar a relação entre as compras de usuários únicos e as compras totais. Foi plotado o gráfico “Compras de Usuários Únicos e Usuários Totais”. Os usuários únicos (aqueles que fizeram uma única compra) está abaixo da linha azul (todas as compras dos usuários), demostrando que parte dos acessos provém de antigos clientes que fazem mais de uma compra no mês. Significa também que o produto/serviço está com dificuldades de atrair novos clientes. Também foi calculado que um novo usuário demora, em média 16 dias para realizar sua primeira compra desde o seu primeiro acesso à plataforma.</p><p>Na “Construção e Análise das Cohorts” foram feitos agrupamentos e filtros nas tabelas, calculado o GP, inserido a idade das cohorts, agrupado e calculado o LTV (Lifetime Value). Isso feito adotando como margin_rate o valor de 50%. Como a primeira cohort do gráfico é a mais completa, a mesma foi selecionada como referência e calculada a soma do período, chegando no valor de 10.20, ou seja, esse é o valor médio que um cliente gerou de receita. Também foi calculado volume médio das vendas, onde analisando as tabelas e heatmap plotados acima, percebe-se que o mês 06–2017 se destaca das demais cohorts om valores acima das demais. Outros destaques são as datas de 09–2017 que apresenta um valor bem atípico (já verificado na análise anterior) e a data de 12–2017 onde apresenta as duas primeiras cohorts com valores mais altos que as demais. Necessário destacar aqui que, como não se sabe detalhes da plataforma/serviço tampouco do público-alvo, uma análise mais aprofundada das causas dos comportamentos demonstrados nos gráficos fica impossibilitada.</p><p>No cálculo do CAC (Customer Acqusition Cost — custo de aquisição de cliente), após filtros e agrupamentos nas tabelas, foi calculado o CAC tomando como referência a mesma cohort do LTV, obtendo um valor de 7.65, ou seja, é o custo médio de cada cliente em marketing. O custo total no período foi de 18.015 por usuário.</p><p>Foram agrupados os custos totais mensais e plotado o gráfico “Custos Mensais no Período” e, ao analisá-lo percebeu-se a semelhança com o gráfico MAU — “Volume de Acessos Mensais”. Plotando ambas as curvas no mesmo gráfico:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*8hmg1llML6FwsGe2NTNVdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*7TdFaAtMLlNun7Qh54zu4w.png" /></figure><p>Após juntar os gráficos percebe-se o comportamento assimétrico entre custos e acessos por fontes. As fontes 1 e 2 apresentam uma performance positiva entre custo/acesso. A fonte 5 um poco maior do que as anteriores. A que se sobressai de todas é a fonte 4 com uma performance excepcional entre custo/retorno. Já a fonte 3, que mais recebeu o dobro de receita comprado à fonte 4, ficou atrás da mesma em quase 20%. As fontes 9 e 10 receberam receitas porém não tiveram retorno.</p><p>No tópico seguinte foi calculado o ROMI (retorno sobre o investimento em marketing). Foram feitos os filtros e agrupamentos necessários para s obter a tabela com a soma acumulada do período. Pela tabela, observa-se que, mesmo os usuários gerando um retorno médio de 10.20 e cada usuário custando ao marketing 7.65 observa-se que o retorno se paga ao longo do período. Isso é verificado pelas tabelas e gráficos, onde nota-se que a cohort do mês 06–2017 demonstra que os investimentos em marketing foram pagos a partir do 6º mês. A cohort do mês 09–2017 continua se destacando com seus valores atípicos. Em média, as cohorts pagam seus investimentos entre 7 e 8 meses.</p><p>Sendo assim, seguem alguns insights para o departamento de marketing otimizar os custos:</p><ul><li>Acessos à plataforma:</li><li>nos dias atuais é imprescindível que todo produto/serviço tenha seu sistema adaptado para mundo mobile. É necessário verificar quais motivos os acessos por esse tipo de aparelho são tão baixo e resolver esses problemas (adaptar site/app, problemas de pagamento, etc);</li><li>Em geral os usuários passam pouco tempo na plataforma. Isso é ruim porque com o curto espaço de tempo o usuário pode não acessar novidades/promoções relacionados aos produtos/serviços. Pesquisas do Google Analytics demostram que o volume de vendas está diretamente ligado ao tempo que o usuário passa visualizando produtos/serviços;</li><li>Fontes de Usuários:</li><li>concentrar os investimentos ns fontes 1, 2 e aumentar o investimento nas fontes 4 e 5</li><li>reduzir o investimento na fonte 3 e eliminar as fontes 9 e 10</li></ul><p>Como não há informações a respeito do produto/serviço bem como do público-alvo a que se destina, não foi possível verificar os motivos da sazonalidade na receita, bem como dos acessos à plataforma, restringindo-se somente a uma análise superficial demonstrada pelos números.</p><p>Se você tem dívidas ou sugestões do projeto, não hesite em me contactar!</p><p>Muito obrigado pela leitura</p><p>Conexões:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=704e7448f9e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Insight de Dados: Prevendo a expansão de uma Rede de Cafeterias com Python e Folium]]></title>
            <link>https://medium.com/@alanjpr/insight-de-dados-prevendo-a-expans%C3%A3o-de-uma-rede-de-cafeterias-com-python-e-folium-ba8643dc18ef?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba8643dc18ef</guid>
            <category><![CDATA[folium]]></category>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 15:08:34 GMT</pubDate>
            <atom:updated>2024-02-23T15:15:36.948Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uma abordagem passo a passo em Python para prever o sucesso da expansão de uma rede de cafeterias do cliente utilizando geolocalização com Geocode e Folium</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*JCJHF65yNoal8yGY.jpg" /></figure><h4>Objetivos do Projeto</h4><ul><li>Investigue as proporções de vários tipos de estabelecimentos;</li><li>Investigue as proporções de estabelecimentos de rede e não;</li><li>Qual tipo de estabelecimento é típico para redes?</li><li>Determine o número médio de assentos para cada tipo de restaurante. Em média, qual tipo de restaurante tem o maior número de assentos? Construa gráficos.</li><li>O que caracteriza redes: muitos estabelecimentos com um pequeno número de assentos ou poucos estabelecimentos com muitos assentos?</li><li>Encontre o número de ruas que têm apenas um restaurante.</li><li>Para as ruas com muitos restaurantes, olhe para a distribuição de número de assentos. Quais tendências você consegue notar?</li><li>Para as ruas com muitos restaurantes, olhe para a distribuição de número de assentos. Quais tendências você consegue notar?</li></ul><h4>O Dataset</h4><p>O conjunto de dados é disponibilizado em formato de arquivo <a href="https://github.com/alanpazribeiro/Estudo-de-Viabilidade-de-Negocio/blob/main/rest_data_us.csv"><em>CSV </em></a>com 9651 linhas de dados.</p><p>O dataset inclui os seguintes campos:</p><ul><li>‘<strong><em>object_name</em></strong>’ — nome de estabelecimento</li><li><strong><em>‘chain’</em></strong> — estabelecimento de rede (TRUE/FALSE)</li><li><strong><em>‘object_type’</em></strong> — tipo de estabelecimento</li><li><strong><em>‘address’ </em></strong>— endereço</li><li><strong><em>‘number’ </em></strong>— número de assentos</li></ul><h3>1 — Início</h3><h4>1 .1 — Importando bibliotecas e conjunto de dados</h4><pre>#Importando bibliotecas<br>import shutup;<br>shutup.please()<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import matplotlib.patches as patches<br>import numpy as np<br>from scipy import stats as st<br>import seaborn as sns<br>sns.set_style(&quot;whitegrid&quot;)<br>import math as mth<br>import re<br>import folium<br>from  folium import Circle, Marker<br>from folium.plugins import MarkerCluster<br>import branca. colormap<br>import requests<br>import time<br>import geocoder<br>from geopy.geocoders import Nominatim<br>from geopy.extra.rate_limiter import RateLimiter</pre><pre>#Carregando o arquivo .csv<br>coffee = pd.read_csv(&#39;/datasets/rest_data_us.csv&#39;, skipinitialspace=True)</pre><h3>2— Explorando os dados</h3><p>Conjunto de dados</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*L30GSIsxK6x9iTvk6GrVlQ.png" /></figure><p>Descrição Geral</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*3EyVirSoaP37HwFVmdCuTA.png" /></figure><p>Informações Gerais do conjunto de dados</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*EU0PBSaov1DNhQ1KZs_1sg.png" /></figure><p>Verificando valores ausentes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*eeslaa7ONY68crdmZJtz9Q.png" /></figure><p>Como verificado acima, há 3 registros com valores nulos. Como trata-se de uma coluna com valores categóricos, não é possível verificar a média/mediana para preencher os valores ausentes nessa coluna. Sendo assim, uma opção seria excluir essas linhas, já que não terá efeito algum no conjunto de dados como um todo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*99h0WRPP_xXP_PfmYxgvNA.png" /></figure><p>Verificando duplicados e valores únicos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*DqvUD3-_ALandS9kQCa5IA.png" /></figure><h3>3 — Analisando o conjunto de dados</h3><h4>3 .1 —Verificando a proporcionalidade dos tipos de estabelecimento</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*o0dFWHxiVti0b87925DYKw.png" /></figure><p>Agrupando por tipo de estabelecimento e calculando o percentual</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*vBnkJGZy_JCjl0sXNsyM_A.png" /></figure><p>Gráfico do Percentual por tipo de estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*09JXZ0VSg2Hy9qy_K1ll6Q.png" /></figure><p>Verificando o gráfico e a tabela acima, percebe-se que mais de 75% de todos os estabelecimentos são compostos por restaurantes, 11% por tipo Fast Food e o tipo Cafeteria com 4,5%.</p><h4>3 .2 — Verificando a proporção dos estabelecimentos da rede</h4><p>Agrupando por tipo de estabelecimento para verificar a proporção pertencente à rede</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*mTuvQIpJPVLc0zs1k0tDDw.png" /></figure><p>Gráfico do percentual dos estabelecimentos pertencentes à rede</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*FQ5qB3qeBFNb8a9vBauUNA.png" /></figure><p>Percebe-se pelo gráfico que menos da metade do total de restaurantes pertencem à rede (31,6%). Nos estabelecimentos tipo Bar a diferença é ainda maior com somente 53,7% pertencentes à rede. Nos estabelecimentos tipo Pizzaria a diferença é de cerca de 5%. A vantagem dos estabelecimentos da rede está nos tipos Fast Food e Café. No estabelecimento tipo Bakery todos pertencem à rede.</p><h4>3 .3 — Verificando a proporção dos acentos dos estabelecimentos da rede</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*nNzrqA5s1nD_qKhSlcqTFg.png" /></figure><p>Agrupando por tipo de estabelecimento para verificar a proporção dos assentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*lI71tFA2U0lzKNeCBdJ2Pg.png" /></figure><p>Gráfico da proporção dos assentos por tipo de estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*AMRx4jOi0bMS7vD3W7-6xA.png" /></figure><p>Calculando a proporcionalidade entre a quantidade de estabelecimentos sendo da rede ou não e o número de assentos, percebe-se que:</p><ul><li>Restaurante: 31% do total de todos os restaurantes pertencentes à rede correspondem a 29,5% de todos os assentos, ou seja, mais restaurantes e menos assentos;</li><li>Pizzaria: 47% do total de todos as pizzarias pertencentes à rede correspondem a 42,5% de todos os assentos, ou seja, mais pizzarias e menos assentos;</li><li>Fast Food: 56% do total de todos as lanchonetes Fast Food pertencentes à rede correspondem a 67,5% de todos os assentos, ou seja, mais assentos por lanchonete;</li><li>Cafeteria: 61% do total de todos as cafeterias pertencentes à rede correspondem a 63% de todos os assentos, ou seja, mais assentos e menos cafeterias;</li><li>Bares: 23% do total de todos os bares pertencentes à rede correspondem a 26% de todos os assentos, ou seja, mais bares e menos assentos;</li><li>Docerias: 100% do total de todos as docerias são pertencentes à rede com 100% de todos os assentos.</li></ul><p>Agrupando por tipo de estabelecimento e verificando a soma dos assentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*PyeC7ELB_-llzRr40qV5ag.png" /></figure><p>Agrupando por tipo de estabelecimento e verificando a proporção total dos assentos de todos estabelecimentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*TKVMcXtMs7C-Hc3grSdeSg.png" /></figure><p>Gráfico do número dos assentos por estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*h-VCzjg6ZCPRdfkt_RJW5g.png" /></figure><p>Pelo gráfico e tabelas acima, nota-se que, do total de todas as categorias somadas, 34,6% dos assentos correspondem a estabelecimentos da rede. Percebe-se também que os estabelecimentos do tipo Restaurante possuem mais assentos e menos restaurantes.</p><h4>3 .4— Número médio de assentos</h4><p>Será verificado agora a média dos assentos dos estabelecimentos pertencentes à rede</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*IdmkxIUaAdKj9aeZdJCYzA.png" /></figure><p>Agrupando e contando os estabelecimentos por tipo e rede e somando os assentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*UJOjjHAywIAGv4eGxshjKw.png" /></figure><p>Calculando a relação entre número de estabelecimentos e quantidade de assentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*hXeUZBL8oxMqSXuQFdHGvw.png" /></figure><p>Gráfico do média dos assentos por estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*hc4O9_hC47gnwgnBFbryTg.png" /></figure><p>Pelos gráficos e tabelas acima, percebe-se que os estabelecimentos da rede possuem menos assentos por estabelecimento em relação aos que não são da rede. Apenas os estabelecimentos tipo Fast-Food e Café da rede possuem uma quantidade de assentos por estabelecimento maior em relação aos que não são da rede. Verifica-se também que nos estabelecimentos da rede há, em média, 39 assentos por estabelecimento.</p><h4>3 .5— Verificando estabelecimentos por localidade</h4><p>Para retirar caracteres especiais e numerações da coluna <strong>“address”, s</strong>erá feita a manipulação e limpeza aplicando <em>Regex</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*0IFVViWQGXLJqW0xfygiWg.png" /></figure><p>Verificando a quantidade de estabelecimentos por localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*W_BWQHQFi0-c9QPRXCTLqA.png" /></figure><p>Gráfico da Quantidade de Estabelecimentos por localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*2Ggd-3dYIjgEe8gr5JIqlA.png" /></figure><p>Após o devido tratamento da coluna ‘address’, extraindo somente o nome das ruas e agrupando por tipo de estabelecimento, é possivel perceber pelo gráfico a distribuição dos estabelecimentos em função das localidades. Nota-se que os tipos de estabelecimentos que possuem a maior quantidade são os restaurantes. Nota-se que a quantidade de restaurantes que não pertencem à rede é mais que o dobro da quantidade dos restaurantes da rede. Nos 3 primeiros endereços (as maiores e mais importantes ruas de LA) a quantidade chega a ser 3x maior.</p><h4>3 .6— Verificando as localidades com o maior número de estabelecimentos</h4><p>Como o objetivo é verificar a viabilidade de um projeto quanto ao seu sucesso, sabe-se que o êxito de um projeto depende de quanto se é visto, ou seja, a quantidade de pessoas que notam o estabelecimento. Sendo assim, uma opção foi verificar as ruas com o maior número de estabelecimentos por tipo.</p><p>Separando as 5 maiores localidades por tipo de estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*j7xdbJn0wJwKN4lwiSqE1g.png" /></figure><p>Fazendo uma lista das localidades</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*z1xpyZXSETS-Jv9_Y06mbQ.png" /></figure><p>Criando um novo dataframe separando as respectivas localidades do dataframe original</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*5whtgD4Nuj302KR1BQODXg.png" /></figure><p>Gráfico tipo boxplot da distribuição dos estabelecimentos por localidade e quantidade de assentos</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hjR5FKGw5awaCVNm7ZbKZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*XpVyyCvNxuOOs7ZPgeDbtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*TmNxbVaMRmoa5aupBIi9Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*pb3PFy2aYwc_HLj_3medGQ.png" /></figure><p>Plotando os gráficos por localidade, quantidade de assentos e tipo de estabelecimento, é possível fazer algumas observações a respeito:</p><ul><li>no primeiro gráfico plotado (tipo boxplot) verifica-se a distribuição da quantidade de assentos por tipo de estabelecimento e por localidade, onde 8 das 14 localidades possuem 75% dos estabelecimentos com até 50 assentos</li><li>todas as localidades possuem mais de 75% dos estabelecimentos com até 100 assentos</li><li>no segundo gráfico (tipo scatterplot) é possível verificar as localidades com a maior quantidade de estabelecimentos e, com isso, um maior movimento de pessoas, ou seja, um maior fluxo de consumidores:</li><li>1 — W PICO BLVD;</li><li>2 — W SUNSET BLVD;</li><li>3 — SANTA MONICA BLVD</li><li>Todas as cafeterias de todas as localidades possuem estabelecimentos com até 50 lugares</li></ul><h4>3 .7 — Verificando as cafeterias</h4><p>Agrupando por tipo de estabelecimento e contando a quantidade de cada um</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*gDNB6DxABdJZy3i4h8rTOQ.png" /></figure><p>Gráfico da quantidade de Cafeterias por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*lL2fivYgbgP5k65aczoEMQ.png" /></figure><p>Filtrando por tipo de estabelecimento ‘Cafeteria’, percebe-se uma grande vantagem dos estabelecimentos da rede sobre os demais. Dos 10 primeiros endereços com mais cafeterias, apenas 3 possuem estabelecimentos que não pertencem à rede e, dos 10, em apenas 1 endereço (‘HOLLYWOOD BLVD’) a rede possui uma quantidade menor de cafeterias.</p><h4>3 .8 — Endereços com o menor número de restaurantes</h4><p>Será verificado as localidades que possuem apenas 1 restaurante, seja pertencente à rede ou não.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*Z6wTCVcgJ6buqftc9wqmMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*0YhLfnGah4oKehml4sSWnQ.png" /></figure><p>Pela tabela acima, percebe-se que há 1112 localidades com somente 1 estabelecimento tipo ‘Restaurante’. Desse total, 456 unidades pertencem à rede.</p><h4>3 .9 — Endereços com o menor número de Cafeterias</h4><p>O mesmo procedimento realizado para os restaurantes acima será agora feito para os estabelecimentos do tipo Cafeteria</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*tNKT2Fmj2Dn_FmZ2ODC0AA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*lwGDohjaOPgcsm4tl6LBtQ.png" /></figure><p>Pela tabela acima, percebe-se que há 214 localidades com somente 1 estabelecimento tipo ‘Cafe’. Desse total, 107 unidades pertencem à rede.</p><h4>3 .10 — Assentos nas localidades com o maior número de Restaurantes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*o1YlpXfQvPbqJDtzZ6ZNqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*3Qc-xwXaLfBumBS_MPpsUw.png" /></figure><p>Gráfico da Quantidade de Restaurantes por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*H4Z1YAUkQvr2twjIi6hYeg.png" /></figure><p>Gráfico da Quantidade de Assentos dos Restaurantes por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*tFbDjXGumRuuYaggCQbaqA.png" /></figure><p>Gráfico da Média da Quantidade de Assentos por Restaurante por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*6FjNGXth_t0WRHaLYed8UA.png" /></figure><p>Pelas tabelas e gráficos plotados acima, é possível verificar como está a distribuição dos assentos por localidade. Algumas observações importantes:</p><ul><li>o primeiro gráfico é exatamente o mesmo plotado n tópico 3.5 (Estabelecimentos por Localidade) onde nota-se a grande quantidade de restaurantes comparado aos demais tipos de estabelecimentos;</li><li>no gráfico 2 observa-se a distribuição de assentos por localidade, onde nota-se uma vantagem de W Sunset Boulevard (mais assentos totais comparado à quantidade de restaurantes) em relação a West Pico Boulevard (maior quantidade de restaurantes e menos assentos totais). Em relação aos restaurantes da rede, todos possuem menos assentos e menos restaurantes por localidade comparado com os que não são da rede;</li><li>já no gráfico 3 (média de assentos por restaurante e por localidade) nota-se uma grande inversão a favor dos restaurantes da rede. Dos 10 listados nas localidades, 6 restaurantes da rede levam vantagem em possuir uma média de assentos maior por restaurante comparados aos restaurantes fora da rede</li></ul><h4>3 .11— Assentos nas localidades com o maior número de Cafeterias</h4><p>Como o objetivo do projeto é atrair investidores para uma rede de cafeterias assessoradas por robôs, a mesma análise feita para Restaurantes foi feita para as Cafeterias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6EKFn9kC3bTpyVTijsjPHg.png" /></figure><p>Gráfico da Quantidade de cafeterias por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*LLFVagJd3tC5Rb19wT0pcQ.png" /></figure><p>Gráfico da Quantidade de Assentos das Cafeterias por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*pGB-EkP6SRZJbfsccPyKtA.png" /></figure><p>Gráfico da Média da Quantidade de Assentos por Cafeteria por Localidade</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Vjl_niNxwFO464S6kCPyyA.png" /></figure><p>A mesma análise feita para os restaurantes foi realizada para as cafeterias com a geração de tabelas e gráficos, onde 9 é possível verificar como está a distribuição dos assentos por localidade. Algumas observações importantes:</p><ul><li>o primeiro gráfico (Estabelecimentos por Localidade) nota-se a grande vantagem dos estabelecimentos da rede em quantidade de cafeterias. Das 15 primeiras localidades, as cafeterias da rede levam vantagem em 11 (dos quais 8 sequer possuem cafeterias fora da rede) e empata em 2 localidades;</li><li>no gráfico 2 observa-se a distribuição de assentos por localidade, onde nota-se uma vantagem em relação às cafeterias da rede, cerca de 90% possuem mais assentos por localidade comparado com os que não são da rede. Hollywood Boulevard e West Pico Boulevard são as localidades que se destacam fora da rede com mais assentos;</li><li>já no gráfico 3 (média de assentos por cafeteria e por localidade) nota-se que a média de assentos está acima dos 20 em praticamente toda as localidades. Novamente uma vantagem das cafeterias da rede.</li></ul><h4>3 .12 — Verificando a localização dos estabelecimentos</h4><p>A localização é fundamental no sucesso ou fracasso de um empreendimento. Ter um estabelecimento bem localizado, próximo a grande circulação de pessoas faz toda a diferença para qualquer ramo de estabelecimento. Com o intuito de enriquecer a análise, optou-se por realizar a verificação plotando os estabelecimentos em um mapa através das informações de geoposicionamento (latitude e longitude).</p><p>Inserindo novas colunas com informações de <em>‘cidade’</em> e <em>‘estado’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*UoXRa2lIPjahOIbQ0-q5KA.png" /></figure><p>Atribuindo as informações de <em>‘city’</em> e <em>‘state’ </em>à coluna<em> ‘address’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Egcx6gG5RJKIibZUE5UTXg.png" /></figure><p>Para obter as informações de latitude e longitude a partir do endereço, será utilizado a API do Google</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*FkS-m0O2ShUffUHCu0Ls2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*uvYSU-2Wszopar4SlGgtHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*jC46N4mbrznDmJ6odptdbg.png" /></figure><p>As informações de latitude e longitude geradas na coluna ‘geocoded’ são do tipo <strong><em>tuple</em></strong>. O próximo passo transformar o tipo de dado e separar as informações em colunas separadas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8U_gFVsba1vqCuKrdbVn2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*PNjuEc_IhT1zYT41-qF9iA.png" /></figure><p>Verificando os valores nulos das novas colunas</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ADwaRD3FFKJd7Xsp-h3eNw.png" /></figure><p>Plotando o mapa com os respectivos pontos de geolocalização</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*mOKSV09nwFIB5fjybpOmBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*PBlroMr9rsK_kEpHY_loyg.png" /></figure><p>Pelo gráfico plotado, onde cada ponto representa um estabelecimento com sua respectiva cor e a linha em azul representam a delimitação dos bairros, nota-se a grande quantidade de restaurantes frente aos demais tipos de estabelecimentos. Nota-se também a distribuição dos estabelecimentos. A grande maioria se concentra na região central de Los Angeles (ponto fixo em verde), tendo sua distribuição mais a noroeste (região de Hollywood e Beverly Hills). Nota-se também que há pouquíssimos estabelecimentos nos bairros a nordeste de Los Angeles (Elysian Park e Angelino Heights), ou seja, mesmo sendo bairros bem próximos à Los Angeles, os turistas preferem frequentar as regiões a noroeste de Los Angeles.</p><p>Plotando o mapa do tipo <strong><em>‘cluster’</em></strong> com as informações agrupadas por tipo de estabelecimento</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*PDwlj5ie8S7_k3qy1GcBog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*v-_gfQ0YbN7qq0JBEZXHDg.png" /></figure><p>Através do mapa acima (tipo clusterizado) onde os pontos são agrupados em uma determinada região delimitada, percebe-se melhor o exposto acima, a grande concentração de estabelecimentos está no centro de Los Angeles. Regiões como Beerly Hills e Hollywood possuem bem menos estabelecimentos se comparado ao centro de Los Angeles (ponto fixo em verde).</p><h4>4— Conclusão</h4><p>O objetivo do estudo foi que se verificassem as condições atuais de mercado afim de atrair investidores para uma cafeteria com atendimento feito por robôs.</p><p>No capitulo 1 foi carregado as bases de dados e bibliotecas que seriam utilizadas na análise.</p><p>No capítulo 2 foi verificado nos conjuntos de dados:</p><ul><li>os valores ausentes e duplicados</li><li>descrição dos dados</li><li>informações gerais</li><li>valores únicos na coluna ‘id’</li></ul><p>Durante a verificação da integridade dos dados, detectou-se que haviam 3 registros com valores nulos. Como trata-se de uma coluna com valores categóricos, não é possível verificar a média/mediana para preencher os valores ausentes nessa coluna. Sendo assim, uma opção seria excluir essas linhas, já que não terá efeito algum no conjunto de dados como um todo.</p><p>No capítulo 3 foram feitas as análises mais aprofundadas. Das explicações nos tópicos acima, alguns pontos interessantes:</p><ul><li>mais de 75% dos estabelecimentos são compostos por restaurantes, 11% por tipo Fast Food e o tipo Cafeteria com 4,5%;</li><li>menos da metade do total de restaurantes pertencem à rede (31,6%). Nos estabelecimentos tipo Bar a diferença é ainda maior com 53,7% pertencentes à rede. Nos estabelecimentos tipo Pizzaria a diferença é de cerca de 5%. A vantagem dos estabelecimentos da rede está nos tipos Fast Food e Café. No estabelecimento tipo Bakery todos pertencem à rede;</li><li>de todos os assentos dos estabelecimentos do conjunto de dados 34,6% pertencem à rede</li><li>31% do total de todos os restaurantes pertencentes à rede correspondem a 29,5% de todos os assentos, ou seja, mais restaurantes e menos assentos;</li><li>Pizzaria: 47% do total de todos as pizzarias pertencentes à rede correspondem a 42,5% de todos os assentos, ou seja, mais pizzarias e menos assentos;</li><li>Fast Food: 56% do total de todos as lanchonetes Fast Food pertencentes à rede correspondem a 67,5% de todos os assentos, ou seja, mais assentos por lanchonete;</li><li>Cafeteria: 61% do total de todos as cafeterias pertencentes à rede correspondem a 63% de todos os assentos, ou seja, mais assentos e menos cafeterias;</li><li>Bares: 23% do total de todos os bares pertencentes à rede correspondem a 26% de todos os assentos, ou seja, mais bares e menos assentos;</li><li>Docerias: 100% do total de todos as docerias são pertencentes à rede com 100% de todos os assentos.</li><li>nos estabelecimentos da rede, há uma média de 39 assentos por estabelecimentos e 46 assentos em média para os não pertencentes à rede;</li><li>analisando as ruas mais movimentadas, nota-se que os tipos de estabelecimentos que possuem a maior quantidade são os restaurantes e que a quantidade de restaurantes que não pertencem à rede é mais que o dobro da quantidade dos restaurantes da rede. Nos 3 primeiros endereços (as maiores e mais importantes ruas de LA) a quantidade chega a ser 3x maior.</li><li>no gráfico plotado (tipo boxplot) verificou-se que 8 das 14 localidades possuem 75% dos estabelecimentos com até 50 assentos e todas as localidades possuem mais de 75% dos estabelecimentos com até 100 assentos</li><li>Todas as cafeterias de todas as localidades possuem estabelecimentos com até 50 lugares</li><li>no gráfico (tipo scatterplot) verificou-se as localidades com a maior quantidade de estabelecimentos e, com isso, um maior movimento de pessoas, ou seja, um maior fluxo de consumidores:</li><li>1 — W PICO BLVD;</li><li>2 — W SUNSET BLVD;</li><li>3 — SANTA MONICA BLVD</li><li>analisando as ‘Cafeterias’ dos 10 primeiros endereços com mais cafeterias, apenas 3 possuem estabelecimentos que não pertencem à rede e, dos 10, em apenas 1 endereço (‘HOLLYWOOD BLVD’) a rede possui uma quantidade menor de cafeterias.</li><li>há 1112 localidades com somente 1 estabelecimento tipo ‘Restaurante’ dos quais, 456 unidades pertencem à rede.</li><li>há 214 localidades com somente 1 estabelecimento tipo ‘Cafe’ dos quais, 107 unidades pertencem à rede.</li><li>na distribuição de assentos por localidade, nota-se uma vantagem de W Sunset Boulevard (mais assentos totais comparado à quantidade de restaurantes) em relação a West Pico Boulevard (maior quantidade de restaurantes e menos assentos totais). Em relação aos restaurantes da rede, todos possuem menos assentos e menos restaurantes por localidade comparado com os que não são da rede. No gráfico 3 (média de assentos por restaurante e por localidade) nota-se uma grande inversão a favor dos restaurantes da rede. Dos 10 listados nas localidades, 6 restaurantes da rede levam vantagem em possuir uma média de assentos maior por restaurante comparados aos restaurantes fora da rede. Um dado importante abaixo é a extensão das ruas:</li><li>West Pico Boulevard — 22km de extensão</li><li>W Sunset Boulevard — 35,2 km de extensão</li><li>WILSHIRE Boulevard — 25,5km de extensão</li><li>Hollywood Boulevard — 7,4km de extensão</li><li>W 3RD ST — 13,5km de extensão</li><li>SANTA MONICA Boulevard — 23km de extensão</li><li>S WESTERN AVE — 41km de extensão</li><li>W Olympic Boulevard — 22km de extensão</li><li>Melrose Ave — 10km de extensão</li><li>S FIGUEROA ST — 32km de extensão</li><li>das 15 primeiras localidades, as cafeterias da rede levam vantagem em 11 (dos quais 8 sequer possuem cafeterias fora da rede) e empata em 2 localidades. Outra observação é que cerca de 90% possuem mais assentos por localidade comparado com os que não são da rede. Hollywood Boulevard e West Pico Boulevard são as localidades que se destacam fora da rede com mais assento. No gráfico 3 (média de assentos por cafeteria e por localidade) nota-se que a média de assentos está acima dos 20 em praticamente toda as localidades. Novamente uma vantagem das cafeterias da rede.</li><li>no último tópico, optou-se obter os pontos de geolocalização via API e plotar os mesmos em um mapa afim de se verificar a distribuição dos estabelecimentos, indicando assim a concentração e fluxo de pessoas. No mapa 1 onde cada ponto representa um estabelecimento com sua respectiva cor e a linha em azul representam a delimitação dos bairros, nota-se a grande quantidade de restaurantes frente aos demais tipos de estabelecimentos. Nota-se também a distribuição dos estabelecimentos. A grande maioria se concentra na região central de Los Angeles (ponto fixo em verde), tendo sua distribuição mais a noroeste (região de Hollywood e Beverly Hills). Nota-se também que há pouquíssimos estabelecimentos nos bairros a nordeste de Los Angeles (Elysian Park e Angelino Heights), ou seja, mesmo sendo bairros bem próximos à Los Angeles, os turistas preferem frequentar as regiões a noroeste de Los Angeles. Já no mapa 2 (tipo clusterizado) onde os pontos são agrupados em uma determinada região delimitada, percebe-se melhor o exposto acima, a grande concentração de estabelecimentos está no centro de Los Angeles. Regiões como Beerly Hills e Hollywood possuem bem menos estabelecimentos se comparado ao centro de Los Angeles (ponto fixo em verde).</li></ul><p>Sendo assim, pela análise e dados expostos acima, há duas possibilidades a serem exploradas no contexto:</p><p><strong>1 —</strong> Opção de implantar o robô barista em uma cafeteria já existente, as melhores localizações seriam:</p><ul><li>W Sunset Boulevard, pois:</li><li>tem início no centro de Los Angeles (centro comercial e financeiro)</li><li>com várias atrações turísticas como museus e estádios</li><li>corta a região de Hollywood e seus diversos parques e atrações ligadas ao cinema, que atrai milhares de turistas e visitantes ao longo do ano todo</li><li>WILSHIRE Boulevard pois:</li><li>seu início é no centro de Los Angeles</li><li>ao longo de sua extensão possui diversos museus próximos</li><li>atravessa vários parques e campos de golfe</li><li>próximo à UCLA</li><li>seu final é no litoral, próximo ao Pier Santa Monica (local de grande fluxo de pessoas)</li></ul><p><strong>2 —</strong> caso opte por um barista robô tipo quiosque, as opções seriam:</p><ul><li>Aeroporto de Los Angeles:</li><li>menos de 30km do centro</li><li>quase 90 milhões de pessoas/ano</li><li>grande exposição e opções para as demais cafeterias existentes</li><li>região de Hollywood:</li><li>cerca de 10km do centro de Los Angeles</li><li>grande concentração de turistas ao longo de todo ano</li></ul><p>Se você tem dívidas ou sugestões do projeto, não hesite em me contactar!</p><p>Muito obrigado pela leitura</p><p>Conexões:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba8643dc18ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hypothesis Testing in data analysis to increase revenue]]></title>
            <link>https://medium.com/@alanjpr/hypothesis-testing-in-data-analysis-to-increase-revenue-8c8f701c389c?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c8f701c389c</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[revenue]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 22:21:47 GMT</pubDate>
            <atom:updated>2024-02-23T15:56:22.906Z</atom:updated>
            <content:encoded><![CDATA[<h4>Prioritizing hypothesis in marketing area that can increase revenue, launching an A/B test, and analyzing the results.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEAzrWlEPclcxJgiHr8t0w.jpeg" /></figure><h4>Introduction</h4><p>Hypothesis testing is an essential technique that assists scientists, researchers, and individuals in general in verifying the validity of their statements or hypotheses about real-world events, aiming to establish new knowledge. In the context of statistics and data science, hypothesis testing techniques are often employed to analyze whether statements about the occurrence of events are true. This includes assessing whether the results derived from machine learning model performance metrics are representative of these models or if they occurred by mere chance.</p><p>Understanding the formulation and testing of hypotheses is crucial not only for establishing the truth of statements but also for gaining new knowledge related to these hypotheses. Additionally, this understanding is valuable for the effective implementation of change management strategies in business processes, aiming to achieve maximum impact.</p><p>This article will delve into some fundamental statistical concepts, providing insights into the involved steps and presenting practical examples related to hypothesis testing. We will explore how to formulate hypotheses correctly and how to apply these tests in real-world scenarios.</p><p>But how do we know which hypothetical value to use as a parameter? How do we determine if this value well represents the studied case or not?</p><p>Furthermore, do you know how to conduct a hypothesis test and in which situations it is applicable? If your answer to these questions is “no,” you are in the right place! In this article, you will learn everything necessary to use this tool.</p><h4>What is a Hypothesis Test?</h4><p>A hypothesis test, also referred to as a statistical test or significance test, is a statistical tool that relies on the use of a random sample extracted from a population of interest. The primary objective is to assess a statement or claim regarding a parameter or characteristic of this population.</p><p>It transcends a mere mathematical comparison between two or more values; rather, it involves the critical examination of whether the value derived from a specific sample signifies a simple random variation from the existing scenario or if it holds broader significance.</p><p>Hypothesis testing finds extensive application in the realm of Statistical Process Control (SPC), operating as a formal procedure embraced by statisticians and data analysts to either accept or reject hypotheses. This process is pivotal for decision-making, allowing professionals to draw conclusions based on sample data and make informed choices about the broader population.</p><p>In essence, hypothesis testing serves as a rigorous and structured approach to validate or refute claims in the face of uncertainty, contributing to the robustness of statistical analysis across various fields.</p><h4>Types of Hypothesis Tests</h4><p>Hypothesis tests can be grouped into two major categories [2]:</p><ul><li>Parametric Tests: These are used when samples follow a normal distribution. Generally, we consider samples to have a normal distribution if the mean is 0 and the variance is 1.</li><li>Non-parametric Tests: These are applied when samples do not follow a normal distribution.</li></ul><p>Depending on the number of samples to be compared, two main categories of hypothesis tests arise:</p><ul><li>One-sample: Applied when there is only one sample to be compared with a specific value.</li><li>Two-sample: Used when there are two or more samples to be compared. In this case, tests may involve correlation and differences between samples. In both cases, samples can be paired or unpaired. Paired samples are also called dependent samples, while unpaired samples are termed independent samples. Paired samples involve natural or matched pairings.</li></ul><p>Typically, parametric tests have non-parametric counterparts. The diagram below reviews how to choose the right Hypothesis Test according to the sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kNmwvY4ud7J_sW2d_4x9YA.jpeg" /></figure><h4>How to Conduct a Hypothesis Test: A Practical Example</h4><p>Let’s consider a scenario where the owner of two pharmacies decided to investigate the customer waiting time in the checkout queue. Over a period of 15 days, he collected data and calculated the average waiting time, finding 5 minutes in store A and 3.5 minutes in store B. Now, the question arises: can we assert that the average waiting time in store B is lower?</p><p>To answer this question in a structured manner, we can formulate two distinct hypotheses:</p><ol><li>Null Hypothesis (H0): The average waiting time is significantly equal in both stores.</li><li>Alternative Hypothesis (Ha): There is a significant difference between the average waiting time in store A and store B.</li></ol><p>From these hypotheses, we can analyze four possible outcomes when conducting the hypothesis test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlSt4r-U6bR_aDOX4akXXg.png" /></figure><ol><li>Accepting H0 when H0 is true: In this case, we conclude that there is no significant difference in the average waiting times between stores A and B.</li><li>Rejecting H0 when H0 is true: This would be a Type I error, indicating that we mistakenly assume a significant difference in average waiting times when, in reality, there isn’t.</li><li>Accepting H0 when Ha is true: This would be a Type II error, indicating that we fail to recognize a real difference in average waiting times between the stores.</li><li>Rejecting H0 when Ha is true: We correctly conclude that there is a significant difference in average waiting times between stores A and B.</li></ol><p>This example illustrates the importance of hypothesis testing in making data-driven decisions, enabling meaningful conclusions about observed differences.</p><h4>How to Make the Right Decision in a Hypothesis Test: Key Details</h4><p>The process of making the correct decision in a hypothesis test is intricate and crucial. To guide this decision, it is essential to understand the variable “p-value.” Also known as the descriptive level or significance probability, it is the probability of obtaining a test statistic equal to or more extreme than that observed in a sample.</p><p>We can assert that when the target value is close to the expected natural variation in the process, the “p-value” is high, indicating the acceptance of H0 and the rejection of Ha.</p><p>The question that arises is: from which value can we consider the “p-value” so small that it allows us to reject the null hypothesis and accept the alternative hypothesis?</p><p>In the commercial realm, this value is called α and is typically set at 0.05, or 5%. In simple terms, this means that the maximum risk of rejecting H0 when H0 is true is 5%.</p><p>It is important to note that the hypothesis test does not provide absolute certainty that the decision made is correct. However, by working with 95% confidence, the probability of making one of the errors is significantly reduced. This approach provides a balance between assertiveness and prudence in decisions based on statistical tests.</p><h4>Project Objective</h4><p><strong><em>From a list of hypotheses, prioritize the one that can increase revenue, launch an A/B Test, and analyze the results.</em></strong></p><h4>About the Dataset</h4><p>1 — Data Used in the Initial Phase of the Project:</p><p>A — a CSV file <strong><em>(</em></strong><a href="https://github.com/alanpazribeiro/Priorizando-Hipoteses-Aumentar-Receita/blob/main/hypotheses_us.csv"><strong><em>hypotheses_us</em></strong></a>) with 9 rows of data:</p><ul><li><strong><em>Hypotheses</em></strong> — Brief Descriptions of the Hypotheses</li><li><strong><em>Reach </em></strong>— User reach, on a scale from one to ten</li><li><strong><em>Impact </em></strong>— Impact on users, on a scale from one to ten</li><li><strong><em>Confidence </em></strong>— Confidence in the hypothesis, on a scale from one to ten</li><li><strong><em>Effort </em></strong>— Resources needed to test a hypothesis, on a scale from one to ten. The higher the Effort value, the more resources are required for the test.</li></ul><p>2 — Data Used in the Second Phase of the Project:</p><p>A — a CSV file (<a href="https://github.com/alanpazribeiro/Priorizando-Hipoteses-Aumentar-Receita/blob/main/orders_us.csv"><strong><em>orders_us</em></strong></a>) with 1198 rows of data.</p><ul><li><strong><em>transactionId </em></strong>— Order identifier</li><li><strong><em>visitorId </em></strong>— User identifier who placed the order</li><li><strong><em>date </em></strong>— Date of the order</li><li><strong><em>revenue </em></strong>— Order revenue</li><li><strong><em>group </em></strong>— A/B test group to which the user belongs</li></ul><p>B — a CSV file (<a href="https://github.com/alanpazribeiro/Priorizando-Hipoteses-Aumentar-Receita/blob/main/visits_us.csv"><strong><em>visits_us</em></strong></a>) with 62 rows of data:</p><ul><li><strong><em>date </em></strong>— Date</li><li><strong><em>group </em></strong>— A/B Test Group</li><li><strong><em>visits </em></strong>— Number of visits on the specified date for the specified A/B test group. Ensure data preprocessing; there may be errors in the original datasets, such as visitors being assigned to both group A and group B.</li></ul><h3>1 — Introduction</h3><h3>1 .1 — Import the libraries and databases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*xDDvU1UsxVVQWRyDeG5oBg.png" /><figcaption>Importing the libraries</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*-8hCnzuN5KwKeMb1qHSUtA.png" /><figcaption>Dataset</figcaption></figure><h3>2 — Analysing the Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*FK1HUqnAGCvQB4r184vaLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*FTJ8MmiiLRMdCZpl-vMBQw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*tTIx9kaxT_NI0A_J0V5Aog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*pbiT0te40pCPku6MIlYGOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*JWYZdy35gXHc0aKF7FqZCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*uu9NGUtDbn8lezMmqjEJxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*FGo9eSi599NNYjbWVwLVdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Sc1yHqM0wmb93vKmADsHLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*qSiY6reYAJNJTnbsvr4imQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*kszpUPQXdMu8YUO7YtWcDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*4za7J6FBp6NxTRv5HT-IfQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*n_Ncxu3iYgArTwm3JdcLcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*xQwd9Utmkr0lSz5VCMXFHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*7HtlngqGNVdHDnHxWdTw_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*qc5UlXQS353E3tth_qlG_w.png" /></figure><p>Through the above checks, the data consistency is evident. There are no null values, missing values, or duplicates. Applying the <strong><em>describe()</em></strong> method reveals the presence of outliers in the ‘orders’ dataset, which will be addressed later.</p><h3>3 Prioritizing Hypotheses</h3><p>As a dataset containing 9 hypotheses has been provided, the ICE and RICE prioritization methods will be applied.</p><h4>3.1 Applying the ICE Method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*0B9mcFya0WszK1cPy40Q7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*2HESUJRNr5PPxv5V_mPoIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*TsDqCJGRyuuygo1G3DIR6Q.png" /></figure><p>Based on the tables from the generated frameworks and the graph above, ICE and RICE differ, especially in the influence of the REACH metric. In other words, when the values for this metric are low, ICE and RICE are practically indifferent. However, when the REACH metric reaches a certain value, it ends up influencing the result. The ICE framework is used when there is no need to differentiate between reach and impact. On the other hand, the RICE framework is used when distinguishing between a feature that can have a significant impact on a small audience and a small impact on a large audience.</p><h3>4 — Analysis of the A/B Test</h3><h4>4.1 Cumulative Revenue Calculation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*JspLBHbnZ4wsNEe1O4u9SQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*4XmMv4q4Q9SSPM1f6JQIYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*tn38zIxWBl0QpMPFWHDiHg.png" /></figure><p>166 duplicate records were found, meaning users who participated in the test in both group A and B simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ZKbHjYNQWLHdysbNgh4tdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*8k7vGDUnFzDEElw0xYBtjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*bowEOoZ0i7w0GHS8IayrsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*vGR_kDh1fqc_tpBBjD9Zsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*hf6p8m2okYhxyyNwDaTtsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*hghMR7cyrFxQlTZf067T0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*9v6dmYZBQRTYnGeTCFM6ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*c0HzbLWL5QFb9JfGAUTYJw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*y06gP3jW_o6v12uaLuMp2w.png" /></figure><p>From the plotted graphs above of the ‘orders’ dataset, examining the revenue behavior of groups A and B, the distortion caused by outliers is evident. When plotting a graph with the mean and median of both groups, it becomes clear that group B had more users making high-value purchases compared to group A. This is further highlighted when plotting the histogram of the data, revealing the significant variability in the data values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*xAJ7wtNs4yuD-c_1Ud3InQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*p-vFA-t7oGOMsSlCLbRSDg.png" /></figure><p>Above, a bar chart of the daily revenue of the two groups was plotted, highlighting the presence of outlier values. There is also a slight advantage of group B over group A in terms of revenue. Additionally, a graph with the total revenue of both groups over the period was plotted, demonstrating the seasonality and variability of revenues throughout the period.</p><h4>4.2 Cumulative Order Calculation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*9_EVOxSuI74il-fuZ3WyAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*6fISWKAQzf4tyHo2EK_m2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ItpjOYUEZ2siNUF4iCKQqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*bADP3timaTIAppxYn_MR5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*lFthgB904SZuHUf4BoE_Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*-B-9MINCD3Nz7t_CXpiVow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*uIyF1l8TDu-yoU8PQRwa-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*vcRJq8TIVF2JM8czpZzShg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*EL4gl84lZpPRxIHsmF4D6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Xu4TXCxl_M3qmVI55pCp2g.png" /></figure><p>The relationship between the number of purchases and accesses is higher in group B than in group A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*_YoJ4ZcaqMqmaJs_MPSeEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*xnDuYBh8bVmQSuj4npckeg.png" /></figure><p>From the tables and graphs generated above, a difference in favor of group B over group A is noticeable, especially when analyzing the revenue and transactions graphs. A slight advantage of group B is evident. Another interesting point is the median of the ratio between visits and revenue: group A has 2.4%, while group B has a value of 3.1%.</p><h4>4.3 Calculating Order Quantity Percentiles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*_vqVHEUl2x8bddxkI4Wpjw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*-WzDdr0-5GHzjZJ1UI_0oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*1oqgQZoWCXuaLQL6I9psFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*oPswXnIqa5nD-OsRqEShLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Db-RLXub2eLCAx9saydPsQ.png" /></figure><p>Applying the <strong><em>np.percentile</em></strong> function and examining the distribution of the number of purchases, it becomes apparent that all users made only one purchase during the period.</p><h4>4.4 Calculating Product Prices Percentiles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*nT1I4SDfbjqSS4T544J7mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*JXWG5YW7EXx9gdEl4YVqqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*neMqShEEWLc_15QKNTgDJQ.png" /></figure><p>Applying the <strong><em>np.percentile</em></strong> function and examining the distribution of purchase values, it is observed that approximately 95% of users made purchases up to 435.54 during the period, and about 99% made purchases up to 900.00 during the period. This is evident in the histogram and scatter plots above, which show that a significant portion of purchases were up to 500.00. Data above this value will be treated as outliers and therefore filtered from the dataset.</p><h4>4.5 Analysis of Cumulative Metrics</h4><p>To assess the stability of metrics over the test period and examine the behavior of the groups, cumulative data is analyzed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*mCgYjZml9bZy0xCw7rhB8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*k6Q6bSM_TnyruiCsbuPCmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*lqwXS4nwl62C5DzI-k4Ekg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*VkDWSgoAdr4uw9ABudBwdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*SNfiOSi2B_6qcp0Ed0tFFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DaBKjFgWQ1LIjCPXgmEfSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*oSCpXroA6vUrJAmEmyZ70w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*WaucEeWMAWfPWlSwA_Oglw.png" /></figure><p>The graph indicates that the group consistently stayed ahead in terms of revenue compared to group A. From the midpoint of the period, there was a significant shift between the lines, possibly due to large orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*5zlUgmU5UGKOE5CTuX6Xxw.png" /></figure><p>From the plotted graph above, it is evident that the cumulative value of the average purchase amounts for the groups shows significant fluctuations, likely due to the presence of outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*BIS4DlcDq9JjXJvbsz84oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*8EO1BF-dT0RwtA2GtPg2Bg.png" /></figure><p>Analyzing the plotted graph above, the discrepancy between the data volumes of groups A and B is noticeable. There is a significant variation that extends throughout the period, with peaks of almost 50% difference between the groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*hQDnh9VFQDyHGm4cIxxZEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*D3YOYDqRUrJG00daqJV2UQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*9wU8LVDcE2CKlbe6wYL00g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*2L9rofEjy_EETONDJO08Lw.png" /></figure><p>From the plotted graph above, it is observed that group B consistently stayed ahead of group A, growing gradually with indications of stability over the period. Group A also shows signs of stability, with a gradual decline in the period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*gbPdagClQlGSiCoX3-lOyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*C3k1ywgL2lvWfyaJeQOiBw.png" /></figure><p>From the graph above showing the relative conversion rate difference between groups A and B, a significant advantage of group B over group A is evident, practically from the beginning of the period. It surpassed 20% for more than 10 days before the midpoint. After that, there was a decline, and in the last days of the period, there are indications of a potential ascent.</p><h4>4.6 Statistical Significance with Raw Data</h4><p>Statistical significance measures the probability that an observed discrepancy between two samples originated by chance. As the purpose of the study is the analysis of an A/B test based on choosing one of the hypotheses that best suits the proposed objective, which is to “Prioritize hypotheses that can increase revenue by launching an A/B Test and analyzing the results.” Thus, the intended hypothesis for analysis will be: “Add product recommendation blocks to the store’s site. This will increase conversion and average purchase size.” This hypothesis was chosen based on the results of the ICE and RICE frameworks and the balance between parameters.</p><h4>4.6.1 Conversion Difference between A and B</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ljpWy3djpny86aDwKsQorA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*YF7laE40iRdmSO-MGbWdog.png" /></figure><p>To conduct the tests, preparation of the databases is necessary. For this, a one-dimensional Series matrix will be created, where each element represents the number of orders made by a specific user (if the customer has not placed any orders, the value assigned to them will be 0). Thus, the number of elements is the number of users, and the sum of the elements is the total number of orders. This procedure will be done separately for each group (A and B).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*zTCIO5Y3Mi0x1emCQCWS5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*P0Wp7h1AJRJH8V_Ow3YvYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*X0oNVM_YYFeGjjZn3bBLZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*d_hSPVzGeBTCShoXY6sesA.png" /></figure><p>Based on the data obtained above, we have:</p><ul><li><strong><em>alpha </em></strong>= 0.05</li><li><strong><em>H0 =</em></strong> There is a significant difference in the conversion rate between the samples</li><li><strong><em>H1 =</em></strong> There is no significant difference in the conversion rate between the samples</li></ul><p>A p-value of 0.0163 was obtained (&lt; 0.05), indicating that there is evidence that the samples from groups A and B have statistically significant differences in conversion rates. Extracting the mean from groups A and B (sample a and sample b) and calculating the relative difference between them, it is found that group B has a conversion rate 15.8% better than group A.</p><h4>4.6.2 Difference in Average Order Size between A and B</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*xcD95zCM4b9uceX-CXWvkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*Xlv1l8jJYA7xtIbvdNMN8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*6XBGfAaXdHclFqiy2LAOPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*4hZ9MxqLC9PmxJF6TSOcfA.png" /></figure><p>Based on the data obtained above, we have:</p><ul><li><strong><em>alpha =</em></strong> 0.05</li><li><strong><em>H0 =</em></strong> There is a significant difference in the average order size between the samples</li><li><strong><em>H1 =</em></strong> There is no significant difference in the average order size between the samples</li></ul><p>A p-value of 0.9232 was obtained (&gt; 0.05), indicating that there is no evidence that the samples from groups A and B have statistically significant differences in revenue volumes. Extracting the average revenue from groups A and B (sample a and sample b) and calculating the relative difference between them, it is found that group B has an average order volume 25.1% better than group A.</p><h4>4.7 Statistical Significance with Filtered Data</h4><p>In the application of the filter, the values calculated in item 4 will be adopted, which are: users who made up to 4 purchases and revenue up to 500.00.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*sJa-MOAdIHm61fmkTzk6AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*lKP0w6VjF6L7OBg7Fkg9ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*-KRlbUKCu3dNkbdDhocIag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*3AikaFbsZjyzdeqswXbqhg.png" /></figure><p>From the plotted graph above showing the distribution of purchases below 500.00, a slight advantage of group B over group A is noticeable, along with the distribution of purchases over the month. Comparing this graph with the one plotted in section 3 before the filter, it is possible to observe the influence of outliers on metric analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*cbDw5usJgG9KCnT87PNc9w.png" /></figure><p>From the generated tables resulting from the proposed filters, the 5 users who made more than 4 purchases during the period are users who also appear in the filtered group of those who spent more than 500.00.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*NG7Elc-mdFcFIrN61YMbcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ZCHouwuiEOSb_U1p92t0zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*RIGBhj1dxB7APgRyxnu-Gw.png" /></figure><p>Comparing the values of statistical significance for the unfiltered data (‘result_conversion’) and the filtered data above (‘result_conversion_filter’), a numerically small difference is noticeable, but approximately 10% in percentage terms. This is because the number of outlier values is small (5 values). Therefore, being a small difference, it did not change the result regarding conversion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*8iyJ6qw7DYcxTxnVUVGjpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*zb-5ukOzaaIqBhjBqsZz0w.png" /></figure><h3>5 — Conclusion</h3><p>The objective of the analysis is to prioritize hypotheses that can increase revenue given a list of hypotheses and, from that, analyze the results of an A/B test. Particularly in the marketing field, an A/B test is used to optimize web marketing strategies, allowing decisions to be made by observing analytical results from the conducted test. From a chosen hypothesis, the results of H0 and H1 for conversion and revenue cases are verified.</p><p>In Chapter 1, libraries and data sets were loaded for the analysis.</p><p>In Chapter 2, the following were checked in the data sets:</p><ul><li>Missing and duplicate values</li><li>Correction of data types (mainly datetime in the databases)</li></ul><p>In Chapter 3, the prioritization of formulated hypotheses was performed. It was observed that the ICE and RICE frameworks differ especially in the influence of the REACH metric. When the values for this measure are low, ICE and RICE are indifferent. However, when the REACH metric reaches a certain value, it ends up influencing the result. The ICE framework is used when there is no need to differentiate between reach and impact. On the other hand, the RICE framework is used when differentiating between a resource that can have a big impact on a small audience and a small impact on a large audience is desired. Since the test’s goal is to increase revenue and based on the numbers presented, test 2 was chosen — “Add product recommendation blocks to the store’s site. This will increase conversion and average purchase size.”</p><p>In Chapter 4, preparations for the A/B test were initiated. Graphs of the ‘orders’ dataset were generated, where the behavior of groups A and B in terms of revenue was analyzed. The distortion of outliers is noticeable when plotting a graph with the mean and median of both groups. Group B had more users making high-value purchases compared to Group A. This is evident when plotting the histogram of the data, showing the great variability in the values.</p><p>A bar chart of the daily revenue for both groups was plotted, revealing the outlier values. A slight advantage of Group B over Group A in terms of revenue is also evident. A graph with the total revenue of both groups over time was plotted, showing seasonality and variability in revenue throughout the period.</p><p>When analyzing the daily transactions separated by group, a slight advantage of Group B (blue) over Group A is noticeable in the number of transactions, with an average of 20.6 (Group B) compared to 17.9 (Group A). Regarding the visits/revenue ratio, when calculating the mean/median of the groups over the period, an advantage of Group B (3.5%) against Group A (2.7%) is also noticeable.</p><p>For the calculation of percentiles in the number of orders, the tables and appropriate calculations were created, and by applying the np.percentile function and checking the distribution of the number of purchases, it is noticeable that almost all users made only one purchase during the period.</p><p>The same procedure was applied to revenue, and it is noticeable that about 95% of users made purchases up to $435.54 during the period, and about 99% made purchases up to $900.00 during the period. This is evidenced in the histogram and scatter plot graphs above, showing that practically most purchases made were up to $500.00. Data above this value will be treated as outliers and filtered from the dataset.</p><p>The cumulative metrics of groups A and B were also verified to check the stability of the metrics. Tables and plotted graphs indicate a significant advantage of Group B over Group A, both in terms of purchase volume (even showing a drop at the end of the period) and in terms of conversion (reaching up to a 20% difference, showing a tendency to rise at the end of the period).</p><p>In Section 4.7, the analysis of statistical significance begins, where the difference in conversion between groups A and B was calculated. After manipulating the tables, we have:</p><ul><li>α = 0.05</li><li>H0 = There are no significant differences in the conversion rate between the samples</li><li>H1 = There are significant differences in the conversion rate between the samples</li></ul><p>A p-value of 0.0168 was obtained (&lt;0.05), demonstrating that there are indications that the samples from groups A and B have statistically significant differences in conversion rates. Extracting the mean of groups A and B (samplea and sampleb) and calculating the relative difference between them, we have that Group B has a conversion rate 15.8% better than Group A.</p><p>For the calculation of the average volume, we have:</p><ul><li>α = 0.05</li><li>H0 = There are no significant differences in the average volume of orders between the samples</li><li>H1 = There are significant differences in the average volume of orders between the samples</li></ul><p>A p-value of 0.9232 was obtained (&gt;0.05), indicating that there are no indications that the samples from groups A and B have statistically significant differences in revenue volumes. Extracting the mean revenue from groups A and B (samplea and sampleb) and calculating the relative difference between them, we have that Group B has an average order volume 25.1% better than Group A.</p><p>Since a large number of outliers were identified in the dataset, there was a need to apply a filter and redo the analysis with filtered data. The applied filters were: up to 4 purchases (5 exclusions) and value up to 500 (46 exclusions).</p><p>A p-value of 0.0141 was obtained. Comparing the statistical significance values of the unfiltered data (result_conversion) and the filtered data above (result_conversion_filter), a numerically small difference between the values is noticeable, but about 10% in percentage terms.</p><p>For the revenue of filtered data, the value was 0.809, an increase of 17% compared to unfiltered data. As for the relative difference between the average volume of orders, it was 0.0155 (a drop of over 90%).</p><p>Based on the above observations, it can be concluded that:</p><ul><li>Regarding conversion, there are statistically significant indications that there has been an improvement in values before and after the applied filters.</li><li>Regarding revenue, there are no statistical indications that there was a significant difference between the groups. Even with an increase in the p-value, there was a 90% drop in relative difference.</li><li>The plotted graphs of the cumulative values of the relative difference in conversion demonstrate a significant advantage of Group B.</li><li>Regarding the relative difference in the average volume of orders, even though Group B shows an increasing trend from the middle of the period, there is a steep drop that persists until the end of the period.</li></ul><p>Based on the above, it can be concluded that there was no improvement in revenue, even though Group B showed a better conversion rate than Group A. As there were many outliers in Group B, one possibility would be to extend the test to verify if the conversion rate is maintained and if there is an improvement in revenue.</p><p>If you have any doubts or suggestions, please don’t hesitate to contact me! Thank you very much for reading!</p><p>Connections:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8f701c389c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing User Behavior in the App and A/A/B Test]]></title>
            <link>https://medium.com/@alanjpr/analyzing-user-behavior-in-the-app-and-a-a-b-test-3970222a5018?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3970222a5018</guid>
            <category><![CDATA[behavior]]></category>
            <category><![CDATA[user-apps]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[funnel]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Tue, 16 Jan 2024 20:25:35 GMT</pubDate>
            <atom:updated>2024-01-16T20:25:35.094Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step using Python, Pandas and Scikit-learn</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ueda0TQtVp09WcQEYV_C8Q.jpeg" /></figure><h3>Introduction</h3><p>User behavior analysis tools play a crucial role in tracking, monitoring, and optimizing various aspects of user behavior within an application. It’s no surprise that many companies are employing these tools to understand their users, enhance user traffic, improve the user experience, and boost revenue.</p><p>Have you ever wondered how users exactly behave in your app? How can you make your digital product better to motivate users to take the desired actions?</p><p>User experience is everything in an app, as approximately 90% of users may choose not to return if they have a poor experience. Understanding how users interact with your app becomes crucial to creating an application that retains user loyalty.</p><h4>Definition — What is User Behavior Analysis?</h4><p>User behavior analysis is the process of collecting and organizing data on meaningful user interactions to determine how they engage with the application. This practice allows you to identify which features are most popular among users and where they may encounter challenges.</p><p>Behavior analysis gathers key metrics and information about user interactions within the app, enabling you to monitor user engagement, measure customer satisfaction, and take proactive measures to enhance overall app performance.</p><p>User analysis is also known as visitor analysis, user experience analysis, or web analysis, encompassing the same analytical data collected from web visitors through various tools and techniques.</p><h4>What Does “Meaningful Interaction” Mean?</h4><p>It refers to any interaction that helps you better understand your users — what they do, why they do it, and how the design and features of your app make this process easier or more challenging. Think of touches, swipes, search queries, time spent on specific screens — the list goes on.</p><p>The goal of user behavior analysis is to discover insights that inform the development of better products. For instance, if you notice many users attempting to use a particular feature but frequently leaving the app after a short period, it may indicate usability issues that need addressing.</p><h4>Project Objective</h4><p>Analyzing user behavior in an app</p><h4>About the Dataset</h4><p>The raw data was provided in the form of a <a href="https://github.com/alanpazribeiro/Analise_comportamento_usuario_teste_AAB/blob/main/Projeto9_database.csv"><em>CSV </em></a><em>file</em> with 244000 rows of data.</p><p>The dataset includes the following fields (each journal entry is a user action or event):</p><ul><li><strong><em>EventName</em></strong> — event name</li><li><strong><em>DeviceIDHash</em></strong> — unique user identifier</li><li><strong><em>EventTimestamp</em></strong> — event timestamp</li><li><strong><em>ExpId</em></strong> — experiment number: 246 and 247 are control groups, 248 is the test group</li></ul><h3>1 — Introduction</h3><h3>1 .1 — Import the libraries and databases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*2TvjBdSDFZOK_Ay-nr8nbQ.png" /><figcaption>Importing the libraries</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*w6jz8HQ10yElX5aYcqU1ew.png" /><figcaption>Dataset</figcaption></figure><p>Verifying dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*8u7ZLvcNcBBvoWrPcMUCjg.png" /><figcaption>Dataset rows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*KPFLY9vmnUwTXxKkAI-nQA.png" /><figcaption>information columns</figcaption></figure><h3>2 — Analysing the Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*0HuhGMEkJuraJh0KM9nGOg.png" /><figcaption>Describe dataset</figcaption></figure><p>Checking for null or missing values in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*zIzqQ9G_VH3AoKeQ7hL3Uw.png" /><figcaption>Null or missing values in dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*IJqo2V6IUr4LwRRgjTqqJQ.png" /><figcaption>Renaming the columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Wh0SxmKrJwf-4TLYRGTcrw.png" /><figcaption>Renaming the fields</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*xk8eSL57gMjv1fcv89VxGg.png" /><figcaption>Unique values</figcaption></figure><p>Transforming Timestamp column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*_sw8F27HbYYcRICFx4X6FQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*QPlpU_FsXsuDhwOhEagMzQ.png" /></figure><p>Creating a new column ‘time’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*XuTwu9xHznu1A8qP37HTxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*aKP19XsZDzKsCUy4zX8Xdg.png" /></figure><h3>3 — Exploring the Data</h3><h4>3.1 — Number os users</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*QU81g2T3-KIBm7q_zxbbMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Fantf8OMJHVvOlsPLNJhxw.png" /></figure><p>According to the tables and charts above, almost 50% of the user quantity is associated with the Main Screen (117,000 users). Analyzing the numbers for the Offers Screen, there is a decrease of 60% compared to the initial values. In the subsequent screens, the percentage reduction is lower (Offers Screen/Product Cart Screen = 8%, and Product Cart Screen/Payment Screen = 19%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*SElmZ36obm7oHK_ETgzjFQ.png" /><figcaption>Number of unique users.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*-SJZmifxdWMHbe2r-nmuOg.png" /><figcaption>Mean of events per user</figcaption></figure><h4>3.2 — Análise Temporal</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*fb8oYeYEjmHSr-B56zahXQ.png" /><figcaption>Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*T-M472Eh3YvTxNbFvH-NGQ.png" /><figcaption>Smallest and largest dates.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*H-KI3zu6P7bYpuxkE3_I_w.png" /></figure><p>Grouping users by event name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*DFZQUVDBVawAJcMBI59JEQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*jco1NwXFEfb3KxL_ni6Flg.png" /></figure><p>Plotting the linear graph of the user quantity at each access stage over the days reveals distinct patterns for each stage, with a noticeable peak in users on the Main Screen. Throughout the period, there are peaks and valleys evident in the behavior of the blue curve (Main Screen). It’s interesting to note that changes in the behavior of the blue curve are not consistently mirrored by the other curves. There is also a significant influence from values before 2019–08–01, posing challenges for a more precise analysis.</p><p>Calculating the daily percentage differences per event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*Yv_7_3KUyA_7vvsMArGuyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*semDRLsngvTeYx_dJuOlow.png" /></figure><p>Examining the graph above, it’s possible to observe a sharp upward trend on 2019–08–01. However, the other days are influenced by the “disturbances” caused by the limited data preceding 2019–08–01.</p><p>Daily percentage distribution of each stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*hX7ajwUIkRHJLvw0lfDVgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*vUFBx30aHp0kgWhh2-jIJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*ujE-EL8qxpiLNwAmHchpPw.png" /></figure><p>By grouping the number of users per hour, one can observe the distribution of users on the site throughout the day. There is an upward trend starting at midnight, followed by a decline around noon, reaching the peak between 2 PM and 3 PM. Afterward, there is a decrease in the number of accesses. The values preceding 2019–08–01, despite being few, may be influencing the graph.</p><p>(This user behavior is likely connected to the type of food sold on the site, requiring a more in-depth analysis.)</p><h4>3.3 — Filtering the dataset and analyzing the stages</h4><p>As observed above, the values preceding 2019–08–01 hindered a more thorough analysis due to their scarcity and sparsity. Therefore, the analysis above will be repeated without these values to achieve a clearer understanding of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*BBzJ2-fYhKMrE7hG20pV0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*MdmK3llW0y68mfJu4AkPRg.png" /></figure><p>Filtering the data from the original dataframe resulted in a reduction of 1.15%. Certainly, these values will not significantly impact future analysis.</p><p><strong><em>3.3.1 — Number of users per day</em></strong></p><p>Number of daily users grouped by event type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*zzjo98gZNzURn9qqol79Ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*-Hxk-DJmJTX3KWD4kwdASw.png" /></figure><p>From the distribution of values on the graph over the days, the user flow pattern is evident. There is a decline from the second day that extends until the fourth day. On the fifth day, there is a significant increase in user flow, extending into the sixth day, when a sharp decline occurs (the most substantial in the period).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*2NriHpraE01yJWBr-HP4eg.png" /></figure><p>Plotting the linear graph of the user quantity at each access stage over the days reveals distinct patterns for each stage, with a noticeable peak in users on the Main Screen. Throughout the period, there are peaks and valleys evident in the behavior of the blue curve (Main Screen). It’s interesting to note that changes in the behavior of the blue curve are not consistently mirrored by the other curves.</p><p><strong><em>3.3.2 — Number of users by event type</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*1L4Wn0ADGGtdich5rA_jTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*8J8YG7dYtrkMoVC9pMeljg.png" /></figure><p>Through the plotted graph above of the daily access quantity per stage, it is possible to more closely examine the same behavior observed in the graph from the previous topic (peaks and valleys). Apparently, the other stages follow the Main Screen stage proportionally. Each day, the stage hierarchies are consistent.</p><p><strong><em>3.3.3 — Daily Percentage Variation</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*wp9JH2WG5SkmAWY9Jzg07g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*-2J0O_nvcuoO3A40k5HXVg.png" /></figure><p>Assigning 0 on the first day as the initial value for all stages, it is possible to observe the percentage variation of each stage over the period. Some interesting points:</p><ul><li>Day 1: The red line (<strong><em>pct_payment</em></strong>) and lilac line (<strong><em>pct_products</em></strong>) show a positive trend, indicating growth in the percentage of accesses, while the blue line (<strong><em>pct_main</em></strong>) and yellow line (<strong><em>pct_tutorial</em></strong>) exhibit a decreasing trend.</li><li>Day 2: The blue line (<strong><em>pct_main</em></strong>), red line (<strong><em>pct_payment</em></strong>), and lilac line (<strong><em>pct_products</em></strong>) show a decline, while the yellow line (<strong><em>pct_tutorial</em></strong>) has an increasing trend.</li><li>Day 4: There is growth in almost all lines (<strong><em>stages</em></strong>) except for the yellow line (<strong><em>pct_tutorial</em></strong>).</li><li>Day 5: There is an inverse behavior compared to the previous day: almost all lines decrease, while the yellow line shows growth.</li><li>Day 6: All lines show a decrease in percentage variation.</li></ul><p><strong><em>3.3.4 — Percentage Distribution of Each Stage Over the Period</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*yv8ovM74iN0oCAg6syOwVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*2g3Cko-nwugTQpsvRonevA.png" /></figure><p>According to the table and graphs plotted above, the daily percentage distribution of the access quantity in each stage over the period is observed. There is symmetry between the lilac curve (Products in Cart) and the red curve (Payment Made). It is also noticeable that the growth of the blue curve (Main Screen) on 08–05 was followed only by the yellow curve (Tutorial) and a decrease in the red (Payment Made) and lilac (Products in Cart) curves. This suggests that users who accessed the site on this day may have encountered some issues with the platform.</p><p><strong><em>3.3.6 — Analysing the stages by hour</em></strong></p><p>Creating a column with time information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*27vxKrCAY0vOEKn1IBw9gQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*82H5Czg8dyIMTUm9Zb-wig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*cUiuXb58_k85Ga_Q0luT5w.png" /></figure><p>Grouping the number of users per hour, one can observe the distribution of users on the site throughout the day. There is an upward trend starting at midnight, followed by a decline around noon, reaching the peak between 2 PM and 3 PM. Afterward, there is a decrease in the number of accesses. The values preceding 2019–08–01, despite being few, may be influencing the graph. Also, some peaks and valleys are now noticeable, which were not visible before due to the values before 2018–08–01.</p><p>This user behavior is likely connected to the type of food sold on the site, requiring a more in-depth analysis.</p><p>Grouping users by access time in each stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*bLnrRG-6uQZzKAuIRXHIqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*24U9qqJc6L_BUwCqcjfUWg.png" /></figure><p>The points mentioned in the above topic become more evident when analyzed by hour. The symmetry between the lilac and red lines (Products in Cart and Payment Made, respectively) is more noticeable. Some interesting points observed:</p><ol><li>The steep slope of the blue curve (Main Screen) both increasing (indicating a sharp increase in accesses in a short period) and decreasing (significant drop in accesses in a short period).</li><li>Compared to the blue curve, the other curves show a more linear slope (below 45°) both increasing and decreasing.</li><li>Another interesting point is at 1 PM, where there is a very steep slope in the lilac and red curves, indicating a flow of more than 1000 people in less than 1 hour, a behavior not followed by the blue curve (Main Screen).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*0ljofnPqB3vpjZVq9E1hhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*YQMBVetXe6-DYyOfvrfsnQ.png" /></figure><p>The graph plotted above makes the points mentioned in the previous topic more evident, showing the percentage distribution of user accesses throughout the day over the entire period. Some interesting points to highlight, especially regarding the behavior of the yellow curve (Tutorial):</p><ul><li>3 AM: The yellow curve surpasses the red (Payment Made) and lilac (Products in Cart) curves; a possible indication that users, after the Main Screen, encountered some kind of problem, either in payment or in cart purchases.</li><li>7 AM: The yellow curve shows an upward trend above all other curves, indicating that users had some kind of problem already on the main screen.</li><li>9 AM, 4 PM, and 9 PM: At these three points, the yellow curve has a positive slope while the others show a negative slope. Probably, users faced an issue at some stage in the purchasing process, accessed the tutorial, and, not finding a solution, simply gave up on the purchase. These three periods are likely the most critical points in the analysis of user behavior, requiring more attention and investigation.</li></ul><p>Calculating the daily percentage differences per event:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*XcyR6mnykYb05SgYQC8Peg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*YKHK6mAL8rLrpj8ASiDmkQ.png" /></figure><p>In the graph plotted above, you can observe the percentage variation in accesses between the current hour and the previous hour, highlighting the points mentioned earlier. Some interesting points:</p><ul><li>5 AM, 11 AM, and 2 PM: The red curve (Payment Made) and lilac curve (Products in Cart) show peaks with a steep positive slope, followed by a sharp negative slope, surpassing the blue curve in percentage variation.</li></ul><p>Users access the platform (blue curve — Main Screen) and check the offers (gray curve — Offers Screen) or vice versa. Some users, already decided, quickly choose their products (lilac curve — Products in Cart) and make the payment (red curve — Payment Made). Some users simply prefer to browse the Main Screen/Offers Screen, and as the choice-payment cycles repeat throughout the day (observed peaks), the number of users gradually decreases, as shown by the gentle slope of the blue (Main Screen) and gray (Offers Screen) curves.</p><p>Further investigation is needed to determine if this behavior aligns with the type of food product the company sells or if it is an anomalous user behavior.</p><p><strong>3.3.7 — Filtered Dataset — Analysis of Experiments</strong></p><p>As seen above, there is an influence of the data before 2019–08–01 when trying to analyze the overall dataset. Therefore, the following analysis will consider the dataframe with data before 2019–08–01 excluded (<strong><em>users_site_drop</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*-AjDqweLa_MaHDjjBsSV_Q.png" /></figure><p>Counting users grouped by experiment number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*C9JENFd4_6AAywivwQd1jQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*N4HcGeJkouc4eLIPzO-a9g.png" /></figure><p>It is noticeable from the graph above that there is a discrepancy in the number of users. The number of users in experiment 248 (lilac) has surpassed experiments 246 and 247 on almost every day.</p><p>Daily percentage distribution of each experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*BkQXixjP-y8o61HurrTSgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*2w1Seyopo1qATCkzJfw8mA.png" /></figure><p>Grouping users by access time in each stage of the experiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*JWhiQEB1ICi4mQ8PTWk05w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*reKR1ieBR-YqobbmHdTQ8w.png" /></figure><p>From the plotted graph above, it is noticeable that user behaviors differ until 6 AM, with some peaks and valleys throughout the day, where the lilac curve stands out. From 5 PM onward, the behavior becomes symmetrical again, with all three curves showing a decline.</p><h3>4 — Funnel Events</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*MMgU8LorzcPVb9gXvRGDUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*WH9BQ5Sh_2JeWYOMANA5tg.png" /></figure><p><strong><em>4.1 — Funnel Events by Stages</em></strong></p><p>On any shopping website, there is a natural and even logical order for users to interact with the site. Regardless of the number of screens and stages the platform/site may have, there is a predetermined order that cannot be escaped. The food website in question is no different. The established order is:</p><ul><li>1st — Main Screen</li><li>2nd — Products in Cart</li><li>3rd — Payment Screen</li></ul><p>It is impossible to reverse this order, meaning it is not possible to make a payment for a product that has not been previously selected (in the cart) or even select such products without accessing the main screen of the platform. That being said, the screens that may possibly generate some uncertainty regarding the normal flow are the Offers Screen and Tutorial Screen.</p><p>The order of stages as mentioned above will be adopted, where the stages will be kept fixed, and only the Tutorial Screen will be alternated (which makes more sense, as issues and doubts on the site can arise at any time during the user’s journey).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*14LYy7483A2mFXNYbTVK7A.png" /></figure><p><strong><em>4.1.1 — Disregarding the Tutorial Event.</em></strong></p><p>Here, we will consider a user who did not use the TUTORIAL, meaning they accessed the MAIN SCREEN up to the PAYMENT MADE SCREEN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*XZL5uGAK-yYE7POfKFD0ZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*XTPkHV8ZZkj57PWKSIQbEg.png" /></figure><p>Only 6% of the users who accessed the site made a purchase, a number considered acceptable.</p><p><strong><em>4.1.2 Tutorial Event in First Stage</em></strong></p><p>Here, we will consider a user who used the TUTORIAL in the first stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*LM5B-SwGf-SFm5gpLtc82A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*JpEDO6e8MHdhclZQ1tRlTQ.png" /></figure><p>Approximately 26% of the users who used the TUTORIAL at the beginning made a purchase. This is likely due to the user feeling more confident after accessing the TUTORIAL.</p><p><strong><em>4.1.3 — Tutorial Event in Second Stage</em></strong></p><p>Here, we will now consider a user who used the TUTORIAL in the second stage during the use of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*AGpWyV94ZXfT-3lCGoMHwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*cliV5XxRLrO-koIYKW1sTQ.png" /></figure><p>Out of 46 users who access the TUTORIAL in the second stage, only 2 make a purchase.</p><p>4.1.4 — <strong><em>Tutorial Event in Third Stage</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*X5ri-DBUEuyY3uUzTfEotg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*QFTEf_cPc1AGzSZtLdGiVw.png" /></figure><p>In this scenario, where the Tutorial Screen is accessed in the third position, only 1 user added any product to the cart, and even then, no purchase was made.</p><p><strong><em>4.1.5 — Tutorial Event in Fourth Stage</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*vI5zWLZTF4CNjM75RbpMFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*fxFU_udQpDueZkZeZZNtpQ.png" /></figure><p>With the Tutorial Screen accessed in the fourth position, out of 1767 users who added any product to the cart after the Tutorial Screen, only 2 completed the purchase.</p><p><strong><em>4.1.56— Tutorial Event in Fifth Stage</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*XkS-CZrzvXz8vjvZEI7jxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*W2XKhNb9QHwOf9GNDXNw_g.png" /></figure><p>Here, the Tutorial Screen is placed last, meaning after the user completes the entire purchase journey. This scenario doesn’t make much sense in the goal of the analysis at hand, as the important aspect is to know how many users made a purchase out of all those who accessed the site. Probably, the user who accessed the Tutorial Screen at this point had some doubts about the delivery time, more product information, or something similar. However, since the purchase has already been completed, this access is irrelevant for the purposes outlined here.</p><h3>5 — Study of Experimental Groups</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*bpla-YGAD5aFNtoD3C0Lfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*PfqhwS6MUFXdSuHsM2krOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*DHEWrgo9mjznvzt_E33Yww.png" /></figure><h4><strong><em>5.1 — The A/A Test</em></strong></h4><p>The A/A test will be conducted to check for differences between the two samples. The test will be performed with values before 2019–08–01 excluded.</p><p>Assumptions:</p><ul><li>alpha = 0.05</li><li>H0 = There is no significant difference between the proportions.</li><li>H1 = There are significant differences between the proportions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*F5K6tOt3ZjSoN3wERM_TNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*PQotyd8Kodz7wlC1e4VSIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*cxYsIbu0LSqWSDfndtisdA.png" /></figure><p>From the table above, it is noticeable that there is a difference between the experiments in user accesses to the stages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*TI2bDPcjGgaTVjx9pDbs8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*XX3NTl9rub49rJ-8h6FkJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*5pxg7JGO4Aw9fcsXjvG0CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*y_4ZhQSo-Y-OGaCqeXAMTw.png" /></figure><p>From the tables and tests conducted above, it is evident that there is no evidence suggesting that the samples from experiments A-246 and A-247 are different.</p><p><strong><em>5.1.1 — Changing the Significance Level</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*6GbFPQ_OBjmK8aYJtSy3xg.png" /></figure><p>Even varying the alpha by ±10%, there was no change in the test results; in other words, there is no evidence that the samples are different.</p><h4>5.2 — The A/B Test</h4><p>It will now be tested the group B-248 with the other experiments to check for differences between the two samples. The test will be performed with values before 2019–08–01 excluded.</p><p>Assumptions:</p><ul><li>alpha = 0.05</li><li>H0 = There is a significant difference between the proportions.</li><li>H1 = There is no significant difference between the proportions.</li></ul><p><strong><em>5.2.1 — A/B test realized by 246 and 248 groups</em></strong></p><p>Unique users by experiment type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*r-7QcPxGB0tKjfvVGRCCEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*PQT4C9SpYy0tqD4DjuFNiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*mbnBrLNy8_b3ZKZrCx0Fog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*_S_KTUJhm5BGglBwVJoM5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*Go7LH9BnwB5RtvWPvcMypA.png" /></figure><p>From the tables and tests conducted above, there is no evidence that the samples from experiments A-246 and B-248 have statistically significant differences between them.</p><p><strong><em>5.2.1.1— Changing the Significance Level</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*s9zf7lu2GtCjEK29Mmn84Q.png" /></figure><p>Even varying the alpha by ±10%, only one event showed evidence of a statistically significant difference between the samples (Products in Cart Screen).</p><p><strong><em>5.2.2— A/B test realized by 247 and 248 groups</em></strong></p><p>Unique users by experiment type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*4xDDHBwg3O2p180_gza7eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*n7uoEvfIhceZhgDlD8FBnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*4epo66vRtkJSr__np3yE1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*QLjBr2Fwjny9nKuzNg-vQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*kmG5PQqelzzhANJId0LDhQ.png" /></figure><p>From the tables and tests conducted above, there is no evidence that the samples from experiments A-247 and B-248 are different.</p><p><strong><em>5.2.2.1 — Changing the Significance Level</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*2Gixvn78nMPFoPDaPWpVKg.png" /></figure><p>Even varying the alpha by ±10%, there was no change in the test results; in other words, there is no evidence that the samples are different.</p><p><strong><em>5.2.3 — Test A/B combining experiments 246 and 247</em></strong></p><p>Unique users by experiment type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*zqem868ocIQAtuk54KDVWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*2uUELIo8JfG3zxuIYfcaIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*jJCeK21hvNKOe09wEzhm2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*yjgrFtH7REpuYRe6sm40LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Yt9GbH4RfQ_amUgh4JeIuw.png" /></figure><p>Above, the z-value and p-value are shown, indicating that there is a difference between the samples. However, the high p-value suggests that there is no statistical evidence to consider the samples different.</p><p><strong><em>5.2.3.2— Changing the Significance Level</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*omZJK1NwYvZkAfQs816RWw.png" /></figure><p>Even varying the alpha by ±10%, there was no change in the test results; in other words, there is no evidence that the samples are different.</p><h3>6 — Conclusions</h3><p>The goal of the analysis is to examine user behavior in the application in order to verify, through the A/B Test, whether there would be a change in user behavior with a page modification. Particularly in the marketing area, an A/B test is used to optimize web marketing strategies, allowing decisions to be made by observing analytical results from the conducted test. Starting with a chosen hypothesis, the results of H0 and H1 are examined.</p><p>In Chapter 1, the databases and libraries to be used in the analysis were loaded.</p><p>In Chapter 2, the following aspects were checked in the datasets:</p><ul><li>Missing and duplicate values</li><li>Data type correction (especially datetime in the database)</li><li>Organizing and renaming columns</li></ul><p>Chapter 3 initiated the Data Study, where in section 3.2, the distribution of total users per stage was examined. According to the tables and graphs, almost 50% of the users are from the Main Screen (117,000). Analyzing the numbers from the Offer Screen, there is a 60% reduction compared to the initial values. In subsequent screens, the percentage reduction is lower (Offer Screen/Product Cart Screen = 8%, Product Cart Screen/Payment Screen = 19%). In section 3.3, the stages per day were examined. Plotting the linear graph of the quantity of users at each access stage over the days reveals the behavior at each stage. It is clear that a large number of users are on the Main Screen. Throughout the period, there are some peaks and valleys demonstrated in the behavior of the blue curve (Main Screen). Interestingly, changes in the behavior of the blue curve are not followed by the other curves. There is also a significant influence of values prior to 2019–08–01, causing difficulty in a more precise analysis. The graphs also show a sharp rise on 2019–08–01, but other days are influenced by the “disturbances” caused by the few data points before 2019–08–01. Grouping the quantity of users per hour shows the distribution of users on the site throughout the day. There is an upward trend starting at midnight, with a decline around noon and reaching the maximum point between 2 pm/3 pm. After that, there is a drop in the number of accesses. Values before 2019–08–01, even though few, possibly influence the graph.</p><p>In section 3.3.2, filtering the data from the original dataframe resulted in a 1.15% reduction (an extremely low value to cause any analysis problems). The linear graph of the quantity of users at each access stage over the days was plotted, revealing the behavior at each stage, where a large number of users on the Main Screen is evident. Throughout the period, there are some peaks and valleys demonstrated in the behavior of the blue curve (Main Screen). Interestingly, changes in the behavior of the blue curve are not followed by the other curves.</p><p>In section 3.3.5 (Daily Percentage Distribution), the behavior of users over time was examined. Assigning 0 on the first day as the initial value for all stages, it is possible to verify the percentage distribution of each stage over time. Some interesting points:</p><ul><li>Day 1: The red (<strong><em>payment_pct</em></strong>) and lilac (<strong><em>products_pct</em></strong>) lines show a positive trend, indicating a growth in the percentage of accesses, while the blue (<strong><em>main_pct</em></strong>) and yellow (<strong><em>tutorial_pct</em></strong>) lines show a decreasing trend.</li><li>Day 2: The blue (<strong><em>main_pct</em></strong>), red (<strong><em>payment_pct</em></strong>), and lilac (<strong><em>products_pct</em></strong>) lines show a decline, while the yellow (<strong><em>tutorial_pct</em></strong>) line has an increasing trend.</li><li>Day 4: There is growth in almost all lines (<strong><em>stages</em></strong>), except for the yellow (<strong><em>tutorial_pct</em></strong>) line.</li><li>Day 5: An inverse behavior compared to the previous day is observed; almost all lines decrease, while the yellow line shows growth.</li><li>Day 6: All lines show a decrease in percentage variation.</li></ul><p>In section 3.3.5 (Daily Percentage Variation), the daily percentage distribution of the quantity of accesses at each stage over time was examined. Symmetry is observed between the lilac curve (Products in Cart) and the red curve (Payment Made). It is also noted that the growth of the blue curve (Main Screen) on 05–08 was followed only by the yellow curve (Tutorial) and a decrease in the red (Payment Made) and lilac (Products in Cart) curves, indicating that users who accessed the site on this day possibly encountered some problem with the platform.</p><p>In section 3.3.7, an hourly analysis was conducted to extract more details about users. By grouping the quantity of users per hour, the distribution of users on the site throughout the day is observed. An ascending behavior starting at midnight, a decline around noon, and reaching the maximum point between 2 pm/3 pm are noted. After that, there is a drop in the number of accesses. Values before 2019–08–01, even though few, possibly influence the graph.</p><p>Some interesting points in the hourly analysis:</p><ul><li>3 am: The yellow curve surpasses the red (Payment Made) and lilac (Products in Cart) curves; a possible indication that users, after the Main Screen, had some kind of problem, either with payment or shopping cart.</li><li>7 am: The yellow curve shows an increasing trend above all other curves, indicating that users had some kind of problem already on the main screen.</li><li>9 am, 4 pm, and 9 pm: At these three points, the yellow curve shows a positive slope while the others show a negative slope. Probably users at some stage in the purchasing process had some problem, accessed the tutorial, and, not finding a solution, simply abandoned the purchase. These three periods are likely the most critical points in the analysis of user behavior, requiring more attention and investigation.</li></ul><p>This user behavior is likely related to the type of food sold on the site, requiring a more in-depth analysis.</p><p>In Chapter 4, the analysis of the Event Funnel was performed, where the order of stages was adopted as follows, keeping the stages fixed and only alternating the TUTORIAL SCREEN stage (which makes more sense, as problems and questions on the site can arise at any time during the user’s journey):</p><ul><li>1st — MAIN SCREEN</li><li>2nd — PRODUCTS IN CART SCREEN</li><li>3rd — PAYMENT SCREEN</li></ul><p>Various scenarios of access to the main screens mentioned above were analyzed, alternating the Tutorial Screen. It was observed, through the values found, that the highest number of users who were converted (made a purchase) was when the Tutorial Screen was in the first position. The event funnel also demonstrated that as the customer progresses through the stages until making a purchase, the lower the likelihood of making a purchase if they access the TUTORIAL SCREEN. This indicates a critical moment in the purchasing process on the site, where, if the user has any problem or doubts regarding the process/product/site, the chances of making a purchase are minimal. This behavior may be related to the fact that the user, having the need to use the TUTORIAL to resolve any doubts or problems, may awaken some insecurity about the product or even the site.</p><p>In Chapter 5, the Experimental Study with the A/A Test and A/B Test was initiated. It was observed that there was a percentage difference between the experiments in user accesses. The calculation of the z-value confirmed the above, showing a high z-value in some stages, but by the p-value values, it was found that there were no statistical indications that the samples were different. Even with variations in alpha (0.01/0.05/0.1), there was no variation in the results. Therefore, it was decided to proceed with the A/B Test, which also showed the same results: high z-value and p-value, also confirming that there were no statistical indications that the samples were different when comparing the old page (sample A) and the new page (sample B).</p><ul><li>Test Results: It is observed that the tests were not successful for some reasons listed below:</li></ul><p>1 - In the A/A Test Insufficient sample size: on average, 35,000 users accessed the site in 7 days. This gives a total of 245,000. Considering the first Test Funnel presented here, without access to the Tutorial screen, we have that 456 users were converted (about 1%). With this, it is noticed that, for a minimum effect detected of 5%, 627,000 accesses are necessary.</p><p>2 — Insufficient test time: from the presented dataset, after cleaning, it was noticed that there was information about user accesses for only 7 days. Based on the data presented above, 35 days of data collection are necessary.</p><p>Some observations and suggestions from the analysis:</p><ul><li>Redo the tests with users so that there is a dataset with greater volume and robustness.</li><li>-Check for possible oscillations/problems on the site at some stages of user purchases.</li><li>Check the issue of the Tutorial Screen, whether it has any influence on the user’s journey (perhaps placing it as a floating pop-up in the lower corner of the screen, always checking the UX).</li><li>Understand what caused the fluctuations at certain times, whether they were site problems or factors inherent to the offered food product.</li></ul><p>If you have any doubts or suggestions, please don’t hesitate to contact me! Thank you very much for reading!</p><p>Connections:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3970222a5018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data to Insight: Predicting Churn with Machine Learning- K-means and RandomForest]]></title>
            <link>https://medium.com/@alanjpr/data-to-insight-predicting-churn-with-machine-learning-k-means-and-randomforest-64a489c994f8?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/64a489c994f8</guid>
            <category><![CDATA[kmeans-clustering]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[prediction-markets]]></category>
            <category><![CDATA[roc]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 13:08:31 GMT</pubDate>
            <atom:updated>2024-01-16T20:26:44.797Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step approach to predict customer attrition using supervised machine learning algorithms in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8cPUUqI1XGAC8bo97lGjoA.jpeg" /></figure><h4>Overview</h4><p>The churn prediction is a useful tool as your company grows and shifts its focus from acquiring new customers to retaining current ones, as it identifies customers at high risk of canceling a subscription or abandoning a product, providing insights into which customers are likely to leave and why.</p><p>Accurate churn prediction models enhance the customer experience and prevent customer loss, resulting in a lower churn rate and higher customer retention, assisting in:</p><ul><li>Predicting churn involves identifying customers at risk of canceling subscriptions or closing accounts.</li><li>A churn model uses customer data and machine learning to identify correlations and predict future behaviors.</li><li>Detecting churn before it happens allows for proactive measures to retain customers, including re-engagement campaigns and personalized education.</li></ul><h4>Project Objective</h4><ul><li>Predict the probability of churn (for the next month) for each customer in a gym;</li><li>Develop user profiles: select the most distinctive groups and describe their main characteristics.</li><li>Analyze the factors that most impact churn.</li><li>Draw basic conclusions and develop recommendations on how to improve customer service:</li><li>1-Identify target groups.</li><li>2- Suggest measures to decrease churn.</li><li>3-Describe any other pattern you notice regarding customer interactions.</li></ul><h4>About the Dataset</h4><p>The raw data was provided in the form of a <a href="https://github.com/alanpazribeiro/Estretegia_retencao_clientes_Machine_Learning/blob/main/Dataset_gym_churn_us.csv"><em>CSV</em></a><em> file</em> with 4000 rows of data.</p><p>The dataset includes the following fields:</p><ul><li><strong><em>‘Churn’ </em></strong>— the churn for the current month</li><li><strong><em>‘gender’</em></strong></li><li><strong><em>‘Near_Location’</em></strong><em> </em>— whether the customer lives or works in the neighborhood where the gym is located</li><li><strong><em>‘Partner’</em></strong><em> </em>— if the user is an employee of a partner company (the gym has partner companies whose employees get discounts; in these cases, the gym stores information about customers who are employees)</li><li><strong><em>‘Promo_friends’ </em></strong>— if the customer originally signed up through a “bring a friend” offer, they typically use the friend’s promo code when paying for the first membership</li><li><strong><em>‘Phone’ </em></strong>— if the user provides their phone number</li><li><strong>‘age’</strong> (age)</li><li><strong><em>‘Lifetime’</em> </strong>— the time (in months) since the first time the customer came to the gym</li></ul><p>Data from the frequency log and purchase data and data about current membership status:</p><ul><li><strong><em>‘Contract_period’ </em></strong>— 1 month, 3 months, 6 months, or a year</li><li><strong><em>‘Month_to_end_contract’ </em></strong>— the remaining months until the contract expires</li><li><strong><em>‘Group_visits’</em></strong><em> </em>— if the customer participates in group sessions</li><li><strong>‘<em>Avg_class_frequency_total’</em> </strong>— average frequency of visits per week for the entire lifetime of the customer</li><li><strong><em>‘Avg_class_frequency_current_month’ </em></strong>— average frequency of visits per week during the current month</li><li><strong><em>‘Avg_additional_charges_total’</em> </strong>— the total amount of money spent on other gym services: coffee, sports goods, cosmetics, massage, etc.</li></ul><h3>1 — Introduction</h3><h4>1 .1— Import the libraries and databases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*4lsTOB6lgxtq6cfTQDQ4ow.png" /><figcaption>Importing the libraries</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*bZoKBG-CL2NHGlQfdYgACQ.png" /><figcaption>Dataset</figcaption></figure><p>Verifying dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*CugDEuDa6AuwL2cCsZmJ8w.png" /><figcaption>Dataset rows</figcaption></figure><p>Dataset information columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*WgFVn9w0BSvDOaVmT7FH4Q.png" /><figcaption>information columns</figcaption></figure><p>Checking duplicates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*FFhv9qvTR-91d_swpm9Kwg.png" /><figcaption>Duplicates</figcaption></figure><p>As seen above, there are no duplicate values in the dataset. However, as mentioned, this dataset spans a complete month, and there is also no identification ID for each customer to confirm the absence of duplicates conclusively. Therefore, it will be assumed that there are no duplicates.</p><h3>2 — Analysing the Data</h3><h4><strong><em>2.1- </em></strong>Analysis of the <strong><em>‘churn’</em></strong> column</h4><p>Information from the ‘churn’ column will now be checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*Gr_BVVKj804vRK3xFrRKbA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Ic-3zrhQT6Irp8doezcgcw.png" /><figcaption>Graph churn</figcaption></figure><p>As checked above, in the ‘churn’ column of the dataset, there are approximately 65% more values with ‘churn’ = 0 (users who did not cancel) than ‘churn’ = 1 (users who canceled). It’s still not possible to determine whether this difference will impact the models’ prediction.</p><h4>2.2 — Analysis of the <strong><em>‘gender’</em></strong> column</h4><p>The information in the ‘gender’ column will be checked now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*S38BXjZIUzzh8mrILeL5SQ.png" /><figcaption>New dataset selected columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*4Fof79QZyFeXGxjOOz7pRw.png" /><figcaption>Nwe column with female information</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*zCzjYodv3cHHvYXBKwX0gg.png" /><figcaption>New dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*BTvqJquXuCDZcYYbarBqXw.png" /><figcaption>Male and Female analysis</figcaption></figure><p>By the tables and graphs plotted above, one can observe a certain balance between the quantities of male and female users, with just a 3% advantage for male users.</p><p><strong><em>2.2.1 — Separating by the Male Gender Age</em></strong></p><p>Analyzing male ages users who canceled and those who did not cancel the plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*tNIk7bdf4Da7wyjPX2y10g.png" /><figcaption>Churn male age gender</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*6RnaSkGvQpTs0m_70M-1PA.png" /><figcaption>Distribution male user by age and ‘churn’</figcaption></figure><p>In the chart above, plotted with data only from male users, the distribution of their ages is noticeable: considering ‘churn’ = 0, more than 42% of users fall within the 28 to 32 age range. However, considering ‘churn’ = 1 (cancellation), the age range with the highest concentration is between 25 to 29 years old. Among male users, the age with the highest number of cancellations is 28 years old.</p><p>2.2.2 — <strong><em>Separating by the Female Gender Age</em></strong></p><p>The same analyzing female ages users who canceled and those who did not cancel the plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Wrw_PFSN6OPAUXn8v1CIzg.png" /><figcaption>Churn female age gender</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*5aHweTxHx9HHyt9nK_1YCg.png" /><figcaption>Distribution female user by age and ‘churn’</figcaption></figure><p>In the chart above, plotted with data only from female users, the distribution of their ages is noticeable: considering ‘churn’ = 0, more than 45% of users fall within the 28 to 32 age range. However, considering ‘churn’ = 1 (cancellation), the age range with the highest concentration is between 25 to 29 years old. Unlike male users, the age with the highest number of cancellations is 25 years old.</p><p><strong><em>2.3 — Analyzing users by location</em></strong></p><p>Now we’ll analyze users by location, that is, users who live near or far from the gym, and by plan cancellations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*5goZE9j4Uwq93EIX_PMp6A.png" /><figcaption>Duplicate the dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*kbl0iG5IaBe90_EHtF53bw.png" /><figcaption>Proportion users by location</figcaption></figure><p>From the above charts and tables, the distribution of users living near the gym is evident, with almost 85% of all users residing nearby. This trend remains consistent between male and female users, with values very close for both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*TXyDrHhV1TB9Hk560MSDVw.png" /><figcaption>Distribution users near location by ‘churn’</figcaption></figure><p>Above, data is checked plotted between the ‘<strong><em>near_location</em></strong>’ and ‘churn’ information where a distribution is noticed between cancellations and users living close to the gym. It’s noticeable that cancellations are much higher among people living near the gym than among those living far away.</p><p><strong><em>2.3.1 — Separating by location and MALE gender</em></strong></p><p>Filtering dataset by male gender</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*NG7z63f5sI-Jza49Rr1eKQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*7Yq30Pws5wiDYX6obds9GQ.png" /><figcaption>Distribution by male gender, far from gym location and ‘churn’</figcaption></figure><p>Analyzing only male users in the graph above who do NOT live near the gym, the predominance of the age range from 28 to 32 years remains for ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age range with the highest concentration shifts to 24 to 28 years. Among male users, the age with the highest number of cancellations for those living close to the gym is 27 years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*UJS6Fda5rn2sdlIF1T9FbA.png" /><figcaption>Distribution by male gender, near from gym location and ‘churn’</figcaption></figure><p>Analyzing the above graph for only male users living close to the gym, the predominance of the age range from 28 to 32 years remains for ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellations), the age range with the highest concentration shifts to 24 to 29 years. Among male users living close to the gym, the age with the highest number of cancellations is 28 years.</p><p>It’s noticeable that the cancellation rate is proportionally higher among those users living close to the gym, approximately 7.5% higher compared to users who do NOT live near the gym.</p><p><strong><em>2.3.2 — Separating by location and FEMALE gender</em></strong></p><p>Filtering dataset by female gender</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*awMWpOsDMrZg9duG6xBARg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*O01mzfKCqQkrwxUgJPRb9Q.png" /><figcaption>Distribution by female gender, far from gym location and ‘churn’</figcaption></figure><p>Analyzing the female users in the above graph, the predominance of the age group 28 to 32 remains when ‘churn’ = 0 (no cancellation). However, considering ‘churn’ = 1 (cancellation), a significant difference is noticed when compared to male users. Here, the age group with the highest concentration shifts to 25 to 30 years old, specifically, the ages with the highest number of cancellations for users who do NOT live near the gym are 25 and 29 years old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Pimh0MzGGbzrPZdHFpe9XA.png" /><figcaption>Distribution by female gender, near from gym location and ‘churn’</figcaption></figure><p>In the graph above, only female users who live near the gym exhibit a predominance in the age group of 28 to 32 when ‘churn’ = 0 (no cancellations). However, considering ‘churn’ = 1 (cancellations), the age group with the highest concentration shifts to 24 to 29 years old. Among female users, the age with the highest number of cancellations for those living near the gym is 25 years old.</p><p>It’s noticeable that the cancellation rate is proportionally higher among users who do NOT live near the gym, approximately 7% higher compared to users living close to the gym.</p><p><strong><em>2.4 — Users from Partner Companies</em></strong></p><p>Now we’ll analyze the user is an employee of a partner company (the gym has partner companies whose employees get discounts; in these cases, the gym stores information about customers who are employees</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*bWNpX_cZZOsGCY1cJf_6cg.png" /><figcaption>New Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*m0cpE4fVilQlDGKQkhj5AA.png" /><figcaption>Partner Company by gender</figcaption></figure><p>From the tables above, one can observe the distribution of users who are participants of partner companies, where a significant balance is noticeable between male and female users, both among those who are from partner companies and those who are not.</p><pre>                 MALE       FEMALE  <br>     PARTNER    24.5%        24.1%<br>  NO PARTNER    26.4%        24.8%</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Fks8Jbpej5JBBi9ysrW7Vw.png" /><figcaption>Distribution users Partner companies by ’churn’</figcaption></figure><p>Above, the plotted data between the ‘partner’ and ‘churn’ information can be observed, where a distribution between cancellations and users who are part of partner companies is noticeable. It’s evident that cancellations are much higher among people who are not part of partner companies compared to users who are.</p><p><strong><em>2.4.1 — Separating by Partners Company and MALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*1dLEw_3N6ouuLaslLKIK9w.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*HPTtWVkNR2Ew5AoABg31Qw.png" /><figcaption>Distribution by male users NOT Partner companies and ‘churn’</figcaption></figure><p>Analyzing only male users in the above graph who are NOT from companies, the predominance of the age range from 28 to 32 years remains when ‘churn’ = 0 (no cancellation). However, considering ‘churn’ = 1 (cancellation), the age range with the highest concentration shifts to 24 to 29 years. Among male users, the age with the highest number of cancellations for those who are NOT from partner companies is 28 years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*mJo9g60JjybCBbxA91dXng.png" /><figcaption>Distribution by male users Partner companies and ‘churn’</figcaption></figure><p>Still analyzing the male users in the chart above who are affiliated with companies, the predominance of the 28 to 32 age range remains in ‘churn’ = 0. Now considering ‘churn’ = 1 (cancellation), the age range with the highest concentration is between 26 to 28 years old. Among male users, the age with the highest number of cancellations among those affiliated with partner companies is 28 years.</p><p>It’s noticeable that the cancellation rate is proportionally higher among those users who are NOT affiliated with partner companies, about 4% higher compared to users who are part of partner companies of the gym.</p><p><strong><em>2.4.2— Separating by Partners Company and FEMALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*mHpvXBC_IWoljM-2QA_XAQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*E1Y3CdzGXwVdfCkQpjSAzw.png" /><figcaption>Distribution by female users NOT Partner companies and ‘churn’</figcaption></figure><p>Analyzing only the female users in the chart above who are NOT affiliated with companies, the predominance of the 28 to 32 age range remains in ‘churn’ = 0. Now considering ‘churn’ = 1 (cancellation), the age range with the highest concentration is between 25 to 29 years old. Among female users, the age with the highest number of cancellations among those NOT affiliated with partner companies is 25 years.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*cmDA2xVSnV0IdJAifa7llg.png" /><figcaption>Distribution by female users Partner companies and ‘churn’</figcaption></figure><p>Still analyzing the female users in the chart above who are affiliated with companies, the predominance of the 29 to 32 age range remains in ‘churn’ = 0. Now considering ‘churn’ = 1 (cancellation), the age range with the highest concentration is between 25 to 27 years old. Among female users, the age with the highest number of cancellations among those affiliated with partner companies is 27 years.</p><p>It’s noticeable that the cancellation rate is proportionally higher among those users who are NOT affiliated with partner companies, about 4% higher compared to users who are part of partner companies of the gym</p><p><strong><em>2.5 — Promo-Friends Users</em></strong></p><p>Now the users participating in the ‘Promo_Friendswill be analyzed, the customer originally signed up through a “bring a friend” offer, they typically use the friend’s promo code when paying for the first membership</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Azz3t1UiPGWUieHpP0N5kQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*UCoeV_EWSGFRMWKWT7lmxQ.png" /><figcaption>Promo_friends by gender</figcaption></figure><p>From the tables above, it’s evident the distribution of users participating in the Friend promotion, showcasing a considerable balance between male and female users. However, there’s a significant difference between those participating in the Friend promotion and those who aren’t</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*U89jVqROjymWolVV39NsIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*IUKeBI1R-lrThkMJyCbxig.png" /><figcaption>Distribution Promo-friends users by ‘churn’</figcaption></figure><p>It seems there’s a significant difference in the cancellation rate between users who are part of the friend referral program (‘partner’) and those who are not involved. If the cancellation rate is much higher among users who don’t participate in the promotion, this could indicate that the friend referral program has a positive impact on user retention. This could be a valuable finding in understanding how incentives or referral programs can influence customer behavior and reduce cancellation rates. This information might be useful for future customer retention strategies or even for adapting existing loyalty programs.</p><p><strong><em>2.5.1 — Separating by Promo-Friends and MALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*05Anm_FMKKdceOFBTBLgrg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*g8-W6XKRDg_gX9acGuZATg.png" /><figcaption>Distribution by male users NOT Promo-friends and ‘churn’</figcaption></figure><p>It seems that among male users who do not participate in the Friend Referral Promotion, the age group of 28 years old is the most common for those who stay (‘churn’ = 0). However, for those who churn (‘churn’ = 1), the predominant range is between 25 and 29 years old. This suggests that within this specific group, male users aged 28 have a higher tendency to stay, while the age group of 25 to 29 has the highest concentration of churn. This analysis by age group and gender could be valuable in understanding behavior patterns among different groups and identifying potential areas to target retention strategies or make adjustments to the loyalty program to better cater to these specific segments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*7HsR4ZHF9JuNUuk0hNCMoA.png" /><figcaption>Distribution by male users Promo-friends and ‘churn’</figcaption></figure><p>Continuing the analysis of male users in the above graph, for those involved in the Friend Referral Promotion, the predominant age range for ‘churn’ = 0 still remains between 28 to 32 years old. However, concerning ‘churn’ = 1 (cancellation), the age group with the highest concentration shifts to the range of 26 to 30 years old. Among male users, the age group with the highest number of cancellations among those affiliated with partner companies is 28 years old.</p><p>It’s noticeable that the cancellation rate is proportionally higher among users who are NOT part of the Friend Referral Promotion, approximately 9% higher compared to users enrolled in the promotion.</p><p><strong><em>2.5.2— Separating by Promo-Friends and FEMALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*j51EsTZrASBaIa3hO93jbg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*o7B22wjOFo6K57ByE_y2ag.png" /><figcaption>Distribution by female users NOT Promo-friends and ‘churn’</figcaption></figure><p>Observing exclusively the group of female users in the chart above who are NOT participating in the Friend Promotion, we notice that the predominant age range, with a ‘churn’ of 0 (no cancellation), remains between 28 and 32 years old. However, when considering a ‘churn’ of 1 (cancellation), the most significant concentration is in the age range of 25 to 29 years. Among female users who do not participate in the Friend Promotion, the age with the highest incidence of cancellations is 25 years old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Q3tGzQjYYlPQGnv2hBSD8A.png" /><figcaption>Distribution by female users Promo-friends and ‘churn’</figcaption></figure><p>Continuing the analysis of female users in the above graph who participate in the Friend Promotion, the prevalent age range for ‘churn’ = 0 remains between 29 and 32 years. However, for ‘churn’ = 1 (cancellation), the age group with the highest concentration shifts to 24 to 27 years. Among male users from partner companies, the age with the highest number of cancellations is 27 years old.</p><p>It’s noticeable that the cancellation rate is notably higher among users who are NOT participating in the Friend Promotion, approximately 8% higher compared to users who are part of it.</p><p><strong><em>2.6 — Phone Contact</em></strong></p><p>It will now be analyzed the users who provided their phone contact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*t-Yyo5Mico0dlmVafR-jRg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*4ucBJhY4mlLhmx1Sp_iwDw.png" /><figcaption>Phone contact by gender</figcaption></figure><p>From the tables above, one can observe the distribution of users who provided their telephone contact information, where a significant balance between male and female users is evident. However, there is a considerable difference between the users who provided their telephone contact and those who did not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*dRzYVtHoPxefbyb7bsqi0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*5Umw0r74onvHT3xFfcYwkg.png" /><figcaption>Distribution by user&#39;s provider phone contact by ‘churn’</figcaption></figure><p>Above, you can see the plotted data between the ‘partner’ and ‘churn’ information, where a distribution between cancellations and users who provided their telephone contact is noticeable. It’s evident that cancellations are significantly higher among people who did not provide their telephone contact compared to users who are part of it.</p><p><strong><em>2.6.1 — Separating by Phone contact and MALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*YfNFGb2iqKhe-5wNDXFbXg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*yHATA6l-yL90HI8rPeeGDg.png" /><figcaption>Distribution by male user’s NOT phone contact by ‘churn’</figcaption></figure><p>Analyzing only male users in the graph above who did NOT provide telephone contact, the predominance of the age range between 28 to 32 remains with ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age group with the highest concentration shifts to 25 to 28 years old. The age with the highest number of cancellations among users NOT participating in the Friend Promotion is 28 years old. It’s still noticeable that there are several ages where cancellation information is missing, resulting in a generally low average.</p><p><strong><em>2.6.2 — Separating by Phone contact and FEMALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*q1hr7Z-w1pYlEPKmD90yQQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*4CHaQQ6vWlOPqVHs7VIRhA.png" /><figcaption>Distribution by female user’s NOT phone contact by ‘churn’</figcaption></figure><p>Analyzing only female users in the chart above who DID NOT provide phone contact, the predominance of the 28 to 32 age range remains with ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age group with the highest concentration is between 26, 27, and 30 years old. The age with the highest number of cancellations among users who DID NOT provide phone contact is 30 years old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*20w2n4CrpZvdCL5vIXzteA.png" /><figcaption>Distribution by female user’s phone contact by ‘churn’</figcaption></figure><p>Still analyzing female users in the chart above who provided phone contact, the predominance of the 28 to 32 age range remains with ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age group with the highest concentration is between 25 to 29 years old. In male users, the age with the highest number of cancellations among those from partner companies is 25 years old.</p><p>It’s noticeable that the cancellation rate is proportionally higher among those users who DID NOT provide phone contact, about 10% higher compared to users who provided phone contact.</p><p><strong><em>2.7 — Participating in group classes</em></strong></p><p>Now we will analyze the users who participate in group classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*E5CRBXSzl2oIg3UGrFrvSg.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*kaU-_hpEe3ZA4FQ-jYHk0A.png" /><figcaption>Users class group by gender</figcaption></figure><p>From the tables above, we can observe the distribution of users participating in group classes, where there is a notable balance between male and female users. However, there is a significant difference between the users involved in group classes and those who do not participate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*uBEir_VLBbJz0bYEb1HL4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AEAzu6URcvoFOOZznVzcLA.png" /><figcaption>Distribution users’ group classes by ‘churn’</figcaption></figure><p>Above, one can see the plotted data between the ‘partner’ and ‘churn’ information, where there is a noticeable distribution between cancellations and users participating in group classes. It is evident that cancellations are much higher among users who do not participate in group classes compared to users who do take part in them.</p><p><strong><em>2.7.1 — Separating by Group classes and MALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*QFSUAuS5hZToSfoxe_jcwA.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*dqwKo7yTT2erO3qGsEYTmw.png" /><figcaption>Distribution by male user’s NOT group classes by ‘churn’</figcaption></figure><p>Analyzing only male users in the graph above, among those who do NOT participate in group classes, the predominance within the ‘churn’ = 0 remains in the age range of 28 to 31 years. However, considering ‘churn’ = 1 (cancellations), the age group with the highest concentration is between 25 to 29 years. The age with the highest number of cancellations among users who do NOT participate in group classes is 26 years. The graph also shows several ages where there is no cancellation information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*IEEDIF4EZZbm10eVmU87xQ.png" /><figcaption>Distribution by male user’s group classes by ‘churn’</figcaption></figure><p>Continuing the analysis on male users in the above graph, among those who participate in group classes, the predominance in the ‘churn’ = 0 category remains within the age range of 28 to 32 years. However, considering ‘churn’ = 1 (cancellations), the age group with the highest concentration is between 27 to 29 years. Among male users participating in group classes, the age with the highest number of cancellations is 28 years.</p><p>It’s noticeable that the quantity of cancellations is proportionally higher among those users who do NOT participate in group classes, approximately 6% higher compared to users who do take part in group classes.</p><p><strong><em>2.7.2 — Separating by Group classes and FEMALE gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*4nPIoT56foyrw2S2f7WgiA.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*H3-ViRuZt0JLfv3y3t4h1Q.png" /><figcaption>Distribution by female user’s NOT group classes by ‘churn’</figcaption></figure><p>Analyzing only the female users in the above graph for those users who do NOT participate in group classes, the predominance of the 29 to 32 age range remains with ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age group with the highest concentration is in the range of 25 to 29 years old. The age with the highest number of cancellations for users who do NOT participate in group classes is 25 years old.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*zlTMIxu2I24-IokJYEi1iQ.png" /><figcaption>Distribution by female user’s NOT group classes by ‘churn’</figcaption></figure><p>Still analyzing the female users in the above graph for those users who participate in group classes, the predominance of the 28 to 32 age range still remains with ‘churn’ = 0. However, considering ‘churn’ = 1 (cancellation), the age group with the highest concentration is in the range of 24 to 29 years old. The age with the highest number of cancellations for users participating in group classes is 27 years old.</p><p>It’s noticeable that the number of cancellations is proportionally higher among those users who do NOT participate in group classes, approximately 5.5% higher compared to users who participate in group classes.</p><p><strong><em>2.8 — Contract Period</em></strong></p><p>Now the period of users’ contracts will be analyzed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*_e9pp2_8hiSaFuo4KbhLmw.png" /><figcaption>Categorization applied</figcaption></figure><p>For a better analysis of the groups, the categorization technique will be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*UnwKXz3m-q3DgDncwe6LSg.png" /><figcaption>Verifying users by gender</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*G21fte2RjhBrOsJVXRjiHw.png" /><figcaption>Proportion users by gender and contract period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*bC6wn1UWQU1zKctbdNqJVQ.png" /><figcaption>Proportion users age and contract period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*2FDiAHaEXet_sbFPa3AWtQ.png" /><figcaption>Distribution users by age and contract period</figcaption></figure><p>Analyzing the tables and the plotted graph above, one notices the distribution of users’ contract durations by age. In the first table regarding genders, it’s observed that 28% of users prefer contracts with durations of up to 1 month, both male and female. Approximately 12% opt for contracts lasting 1 year (male and female). In the second table depicting ages, it’s evident how the duration type is distributed among different age groups. The significant predominance of short-term contracts (1 month) is noted, especially within the age range of 28 to 30 years old.</p><p>Reviewing the above-plotted graph, the previously mentioned observation is confirmed, where the vast majority of users opt for short-term contracts. Users up to 23 years old almost exclusively choose this option, with other duration values being insignificant. From the age of 34 onwards, a higher number of users show a preference for longer contracts, indicating a smaller difference in the graph between short-term contracts and others. This suggests the preference of this age group for longer-duration contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*WLXmQjJv-P_cWNJFwdnOkw.png" /><figcaption>Distribution users by contract period</figcaption></figure><p>Above, we see the data plotted between the ‘partner’ and ‘churn’ information, where a distribution between cancellations and users with their contract durations is noticeable. It’s evident that cancellations are significantly higher among users with short contract durations compared to other durations.</p><p><strong><em>2.8.1— Separated by Contract Period and MALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*c_8OLmUGwS7XEGuHepvRBQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*-ebjd5SxXVIqMXK01hvmeQ.png" /><figcaption>Filtering by ‘churn = 1‘, grouping by contract period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*dAOcPpl5X0-uhlwCiYhGUg.png" /><figcaption>Graph by contract period and age and churn</figcaption></figure><p>In the plotted graphs above, the quantity of male users is distributed by age and contract duration, both for those who did not cancel (churn = 0 — left) and those who cancelled the contract (churn = 1 — right). The prevalence of contracts up to 1 month is noticeable across nearly all ages. There’s an interesting trend where from ages 19 to 27, there’s almost an equal preference between short-term (1 month) and medium-term contracts (up to 6 months), except for 26-year-old users (where the majority prefers short contracts). From ages 28 to 34, the vast majority prefers contracts up to 1 month, and from 35 onwards, the difference becomes smaller again. It’s interesting to note that users aged 38 and 39 almost exclusively prefer medium and long-term contracts.</p><p>Analyzing cancellations (churn = 1), it’s observed that users with short contracts cancel much more across all ages. It’s noticeable that users with long-term contracts (up to 12 months) have almost no cancellations, except among 26-year-old users. For cancellations in contracts with medium duration (up to 6 months), there’s a prevalence among 28-year-old users.</p><p><strong><em>2.8.2 — Separated by Contract Period and FEMALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*D31caSpqmy1jhk7vsA3ImQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*9f20AbILeD12rhwNRMmNMg.png" /><figcaption>Order by age and contract period</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*sGFpglfgC_r_svFhzrRI2g.png" /><figcaption>Distribution by age, contract period and ‘churn’</figcaption></figure><p>Analyzing the behavior of female users for the same type of graph, a similar pattern to male users is noticed, where the majority of users opt for short-term contracts (up to 1 month). Up to 24 years old, users tend to choose more medium and long-term contracts, and after 25 years old, users opting for short-term contracts become the majority across all ages.</p><p>Regarding cancellations (churn = 1), as expected, users with short-term contracts cancel much more across all ages. It’s noteworthy that users with long-term contracts (up to 12 months) experience almost no cancellations, except among users aged 26 to 28. For cancellations in contracts with medium-term duration (up to 6 months), there is a prevalence among 26-year-old users, different from male users.</p><p><strong><em>2.9 — Remaining month until expires contract</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*GPppUM7qgzRQU1aEiXl_-w.png" /><figcaption>Filtering dataset</figcaption></figure><p>For a better analysis of the groups, the categorization technique will be applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*IzvAhjeha4dgt4FoKfx-0A.png" /><figcaption>Categorising remaining month to end contract</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*XzSXSYgKCVUct9sDlHZk-Q.png" /><figcaption>Verifying users by gender</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*mFVI9fV5TJmDwr08Ij0Krw.png" /><figcaption>Distribution by age and remaining month to end contract</figcaption></figure><p>Analyzing the tables and the plotted graph above, one notices the distribution of contract end months for users by age, confirming what was mentioned in the previous topic, where the majority of users opt for contracts with a duration of up to 1 month, following the previously mentioned proportions. It’s worth highlighting here regarding contracts with a duration of over 6 months, where it’s noticeable that at practically every age, users who opted for this duration fall within the 7–9 month range for the respective contract terminations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*bd2rTtG3c29emHICRBP7eQ.png" /><figcaption>Distribution by remaining month to end contract</figcaption></figure><p>Above, you can see the data plotted between the ‘partner’ and ‘churn’ information, where there’s a noticeable distribution between cancellations and the months remaining for user contracts to expire. As mentioned above, cancellations are significantly higher among users with fewer months remaining on their contracts.</p><p><strong><em>2.9.1 — Separated by Remaining month until expires contract and MALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*gdijNXMJwf-PwWGX_JEWhQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*0YB0g6YjkrOwCaGw7ooJ_w.png" /><figcaption>Table by users age and remaining month to end contract</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*a7C34ongzV1xAblaz809JQ.png" /><figcaption>Distribution by male users and age and remaining month to end contract and ‘churn’</figcaption></figure><p>No graphs plotted above, the quantity of male users is distributed by age and contract duration, both for those who did not cancel (churn = 0 — left) and those who canceled the contract (churn = 1 — right). The prevalence of contracts lasting up to 1 month is noticeable across almost all ages. From 19 to 25 years old, the difference between the groups is small, confirming what was previously mentioned regarding user ages and their contract type preferences. From 26 years old, the number of contracts ending within 3 months is much higher than other groups, both for those who did not cancel (churn = 0 — left) and those who canceled the contract (churn = 1 — right). From 28 to 34 years old, the majority prefer contracts lasting up to 1 month, and from 35 years old, the difference becomes small again, following the behavior analyzed in the previous section. It’s interesting to note users at 38 and 39 years old, where almost all prefer medium to long-term contracts.</p><p>Analyzing cancellations (churn = 1), it’s observed that users with short contracts cancel much more across all ages. It’s noticeable that users with long-term contracts (10 to 12 months) have almost no cancellations, and users with contracts ending within the range of 7 to 9 months canceled across all ages. In cancellations of medium-term contracts (up to 6 months), there’s a prevalence of users at 28 years old.</p><p><strong><em>2.9.2 — Separated by Remaining month until expires contract and FEMALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*PzkDLiBs3hHBM3xX2DEn1w.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*D8-DRht4-FcwBhj0BXY1vA.png" /><figcaption>Table by users age and remaining month to end contract</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*S2U4cQLEhGu_cr9IxK4fOQ.png" /><figcaption>Table by female users age and remaining month to end contract</figcaption></figure><p>Analyzing the behavior of female users for the same type of chart, a similar pattern to male users is noticed, where the prevalence of users with contracts ending within the 0–3 month range is evident. Up until the age of 25, the ranges of contract end months are equivalent, and from the age of 26 onwards, the range of contracts ending within 3 months stands out. It’s worth noting that there is a balance between the 4–6 month and 7–9 month ranges.</p><p>Examining the cancellations (churn = 1), as expected, users with contracts ending within the 0–3 month range cancel much more across all ages. It’s noticeable that for users with long-term contracts (up to 12 months), there is almost no cancellation, except among users aged 26 to 28. In cancellations of contracts ending within the 7–9 month range, there’s a prevalence among 25-year-old users.</p><p><strong><em>2.10 — Months until the contract expires</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Bk1fLNSHBWFLn1NDTvLVVA.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*s8fUitNximr7p-vIEhUdXA.png" /><figcaption>Graph by quantity and <em>Months until the contract expires</em></figcaption></figure><p>In the table and graph plotted above, the distribution of users by the number of months since their first visit to the gym is observed. It represents how long, in months, the user has been associated with the gym. There’s a significant number of users with a short relationship period, where users with up to 5 months of association account for over 77% of the total user base at the gym. This is likely a reflection of the type of contract that the vast majority of users choose (validity of up to 1 month). This becomes problematic as this high turnover affects customer retention negatively</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Zappec382s9_GKk_q4lhDQ.png" /><figcaption>Categorizing m<em>onths until the contract expires column</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*_4ConCftygvP9LJ_7yNzdA.png" /><figcaption>Verifying users by gender</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*FjHPBNFvBaNKczgGtUq3fw.png" /><figcaption>Proportion users by gender and m<em>onths until the contract expires</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*orbET87l8yNZdn5RnFOSJQ.png" /><figcaption>Proportion users by age and m<em>onths until the contract expires</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*R-D1UI_MISzhmeT9CSrUTQ.png" /><figcaption>Distribution users by age and m<em>onths until the contract expires</em></figcaption></figure><p>It’s interesting to note in the graph above that, despite confirming what was previously mentioned, it also shows that there are users who have been using the service for a long period, indicating a prolonged relationship with the gym. The users in question (in the 26–30 months range) appear around the age of 24 and extend up to 37 years old, with the highest concentration of users peaking at the age of 31.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*QoFdpXOqgdakZUau8pRqEQ.png" /><figcaption>Distribution users by m<em>onths until the contract expires</em></figcaption></figure><p>Above, the data plotted between the ‘lifetime’ and ‘churn’ information is observed, where a distribution between cancellations and the users’ service usage time is noted. As evidenced above, it is noticeable that cancellations are significantly higher among users with a short service usage time compared to others.</p><p><strong><em>2.10.1 — Separating by Months until the contract expires and MALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*2NkWhCilVWcCj7PdGrLQ2A.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*qP9yfdket--1AIfwghFX9w.png" /><figcaption><em>Separating users by age and by months until the contract expires and MALE Gender</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ZWd_D5ORdOJ70ZOVkgEbsg.png" /><figcaption>Distribution users by age <em>and by months until the contract expires and churn = 0</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*IRVdCBk9RiNY7nsRzpBVug.png" /><figcaption>Distribution users by age <em>and by months until the contract expires and churn = 1</em></figcaption></figure><p>In the graphs above, besides the groups with service usage months 0–5 and 26–30 exposed in the previous topic, analyzing only male users (churn = 0), one can also notice a concentration of users with 26–30 months of usage, among users aged 29 (peak). The range of 6–10 months of usage appears in third place, also peaking at the age of 29.</p><p>For male users who churned (churn = 1), it is noticeable that almost all of them had a short-term usage of months (0–3), with the peak occurring at the age of 28 and extending to 35. There are a few users with usage months 6–10 distributed between 26–27 and 31–33 years old.</p><p><strong><em>2.10.2 — Separating by Months until the contract expires and FEMALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DrrDjOq8XHUeB8JmIeeBFQ.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*OIF5gHbu57jQ_HEunDkWAw.png" /><figcaption><em>Separating users by age and by months until the contract expires and FEMALE Gender</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*hTs6Ih5CDe7yy0AKqmWE1g.png" /><figcaption>Distribution users by age <em>and by months until the contract expires and churn = 0</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*fWRfHSDqfEo4AryPU2Yv3A.png" /><figcaption>Distribution users by age <em>and by months until the contract expires and churn = 1</em></figcaption></figure><p>In the graphs above, besides the groups with service usage months 0–5 and 26–30 exposed in the previous topic, analyzing only female users (churn = 0), there’s a higher distribution among the ages of users with usage months in the range of 26–30, peaking in the quantity of users between 29 and 30 years old. The same trend is observed among users with usage months in the 6–10 range.</p><p>As for female users who churned (churn = 1), it is noticeable that almost all of them had short-term usage of months (0–3), where the peak also appears at the age of 28. There are a few users with usage months 6–10 at the age of 30.</p><p><strong><em>2.11 — Average amount spent by users on other services</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*NgHiyjFE1aesI3uJPwnSJA.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*A_ohqMaI6Y6TRdGJrMrj5w.png" /><figcaption>Table users by age and a<em>verage amount spent on other services</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*_OOXed3Q1K-PRl7dJclxRA.png" /><figcaption>Table users by age and a<em>verage amount spent on other services by ‘churn’</em></figcaption></figure><p>Here is the percentage distribution of various expenses by users based on age and gender (gender_0 = Female / gender_1 = Male), where it’s noticeable that the highest percentage of expenses falls within the age range of 27 to 32, for both females and males.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*BkK1GfntPkgdRg-cvwky6g.png" /><figcaption>Table users by age and a<em>verage amount spent on other services by ‘churn’</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*m3a7owMEcgcsYOEGgkiezA.png" /><figcaption>Boxplot by users age and a<em>verage amount spent on other services by ‘churn’</em></figcaption></figure><p>Here’s the analysis considering the percentages of spending by gender (gender_0 = Female / gender_1 = Male) across each age group. Some important observations:</p><ul><li>Considering the entire age range of users (18–41), women show a higher percentage of spending than men in 7 age groups.</li><li>At ages 18 and 41, 100% of the spending is done by women.</li><li>From ages 27 to 32, where the highest spending percentage occurs across all age groups, there’s a balanced spending percentage between genders.</li><li>Excluding the extremes (18 and 41 years), the largest percentage differences between genders are in the age groups of 19, 20, and 37 in favor of men, and 23 years in favor of women.</li></ul><p>In the boxplot graph above, the distribution of spending percentages at each age among users is also observed. It’s noticeable that until 24 years old, there’s a considerable variation in spending across ages. From 25 to 36 years old, approximately 75% of users spent just over 200.00, and beyond 37, the spending of 75% of users is above 250.00. It’s interesting to note that all outliers appearing in the graph are between the ages of 24 to 32.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*XY4XQn6Kx0RC-SM_aIbA2A.png" /><figcaption>Distribution users by age and a<em>verage amount spent on other services</em></figcaption></figure><p>Above is the age distribution of the total expenses of users on other services at the gym. It’s observed that those who spend the most on additional services are users in the 27 to 32 age range, complementing the analysis above with the tables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*LkB11eri3YwyfM9YxBL4Cw.png" /><figcaption>Distribution users by a<em>verage amount spent on other services</em></figcaption></figure><p>Above, we see the data plotted between the ‘avg_additional_charges_total’ and ‘churn’ information, where the distribution between cancellations and average spending on various services is noted. It’s noticeable that cancellations are primarily concentrated among users spending around 50.0.</p><p><strong><em>2.11.1 — Separating by Average amount spent by users on other services and MALE genre</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*synwI25lRcjjW2IEzen5OA.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*FDkREBICTjIDAnVTLXkQpw.png" /><figcaption>Distribution users MALE gander by age and a<em>verage amount spent on other services and ‘churn’</em></figcaption></figure><p>According to the information above, for male users who didn’t cancel (churn = 0), the highest expenses are concentrated in the 28 to 32 age range, with very low values at the extremes. However, for users who canceled their plan (churn = 1), the highest expenses are in the 24 to 30 age range, and from the age of 34, there seems to be no spending on various services</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*hdpcQoEoSVtRreDAXrwUcw.png" /><figcaption>Distribution users FEMALE gander by age and a<em>verage amount spent on other services and ‘churn’</em></figcaption></figure><p>According to the information above, for female users who didn’t cancel (churn = 0), the highest expenses are also concentrated in the 28 to 32 age range, with no values between the ages of 8 to 21. However, for users who canceled their plan (churn = 1), the highest expenses are in the 25 to 29 age range, and from the age of 34, there seems to be no spending on various services</p><p><strong><em>2.12 — Average week frequency per month</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*sgdNALAQHsOemH6lTON77Q.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*q2j9P5-ai8_tSWZmXJvYTg.png" /><figcaption><strong><em>verage week frequency per month</em></strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*bSGf61zJ3g_0bOt3AtDToA.png" /><figcaption><em>Boxplot by age and average week frequency per month</em></figcaption></figure><p>In the boxplot above, the distribution of average weekly frequency among users at different ages is observed. It’s noticeable that until the age of 24, there’s a significant variation in spending among ages. From 25 to 36 years old, around 75% of users spent just over 200.00, and above 37, 75% of users spent over 250.00. It’s interesting to note that all the outliers appearing on the graph are between the ages of 24 to 32. Between the ages of 20 and 24, approximately 75% of users in this age range attend the gym up to 2 times a week. After this age, the average frequencies increase across ages, and from 30 to 34, they reach a stability, with an average frequency above 2.5 times per week. The most consistent age is 39, with 75% of users having a frequency close to 4 times per week</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*bTnUpN6zrnGAIgVryIQSxA.png" /><figcaption><em>Distribution by age and average week frequency per month</em></figcaption></figure><p>The chart above reinforces what was stated in the boxplot regarding the average frequencies of users by age. Notice at the extremes the ages 18 and 19 with very low weekly frequencies, while 39-year-old users have average frequencies above 3.5 times per week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*gYZTOIb5Bw6LqtbMb4pBlQ.png" /><figcaption><em>Distribution by average week frequency per month</em></figcaption></figure><p>Above, you can see the data plotted between the <strong><em>‘avg_additional_charges_total’</em></strong> and <strong><em>‘churn’</em></strong> information, where there is a noticeable distribution between cancellations and the average weekly frequency of users. It’s noticeable that cancellations are concentrated mainly among users with a frequency between 1x and 1.5x per week.</p><p><strong><em>2.12.1 — Separate Average week frequency per month by MALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*92lQp0P7wEEMZeyczO8E-g.png" /><figcaption><em>Distribution by users MALE by age and average week frequency per month and ‘chrun’</em></figcaption></figure><p>Above, one can observe the distribution of male average weekly frequency by age. For churn = 0, the ages with the highest frequency are 22 years and 39 years. From the age of 23, there’s a balance of ages around a frequency of approximately 2 times per week. For churn = 1, a good portion of users has an average weekly frequency below 1, except for the ages of 21, 30, and 33 years with an average weekly frequency above 1</p><p><strong><em>2.12.2 — Separate Average week frequency per month by FEMALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*jA6MSim9kDRY446ln-PgRA.png" /><figcaption><em>Distribution by users FEMALE by age and average week frequency per month and ‘chrun’</em></figcaption></figure><p>Above, you can observe the distribution of female average weekly frequency by age. For churn = 0, the ages with the highest frequency are 37 and 38 years old. There’s no record of weekly frequency for ages below 22 years. From the age of 28, there’s a balance of ages around 2 times per week in frequency. For churn = 1, a good portion of users has an average weekly frequency below 1, except for the ages of 35 and 38 years old with an average weekly frequency above 1.5.</p><p><strong><em>2.13 — Average week frequency entire period</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*hCcsflcc8oLwGG56-caTfw.png" /><figcaption>Filtering dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*lgI5UCwN7-koTz2V5RUjfA.png" /><figcaption>Table by age and a<em>verage week frequency entire period</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*Y0iNCFRgM4cDYIkEnhbCqQ.png" /><figcaption><em>Boxplot by age and </em>a<em>verage week frequency entire period</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*EI0VZax7uVN5b3ma7lvgyw.png" /><figcaption><em>Distribution by age and </em>a<em>verage week frequency entire period</em></figcaption></figure><p>According to the boxplot chart above, plotted with total average frequencies by age, one can observe the percentage frequency behavior of the users. There’s a significant variation in the percentages from 18 to 22 years old, where 50% of users have an average frequency around 1.5 times per week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*-QykAXNWQDJ79VGTtVj9Gw.png" /><figcaption>Distribution by a<em>verage week frequency entire period</em></figcaption></figure><p>Above, you can see the data plotted between the <strong><em>‘avg_class_freq_total’</em></strong> and <strong><em>‘churn’</em></strong> information, where there’s a distribution between cancellations and the users’ average weekly frequency. It’s noticeable that cancellations are mainly concentrated among users with a frequency between 1x and 1.5x per week.</p><p><strong><em>2.13.1 — Separate Average week frequency entire period by MALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*6mY9hJ6Qn3XAfwMx1Y2I7w.png" /><figcaption><em>Distribution by users MALE by age and </em>a<em>verage week frequency entire period and ‘chrun’</em></figcaption></figure><p>Above is a plotted graph of the total weekly frequency of male users. A higher frequency is noticeable at the extremes of the graph (22 years and 39 years), and from the age of 26, there’s a certain balance in the total average weekly frequency. In users who canceled, the average weekly frequency is around 1.5 times per week</p><p><strong><em>2.13.2 — Separate Average week frequency entire period by FEMALE Gender</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*NMFppPrZilx_oWoi357TKA.png" /><figcaption><em>Distribution by users FEMALE by age and </em>a<em>verage week frequency entire period and ‘chrun’</em></figcaption></figure><p>Above is a plotted graph of the total weekly frequency of female users. There is also a higher frequency noticeable at the extremes of the graph (22 years and 39 years), and from the age of 26, there’s a certain balance in the total average weekly frequency. In users who canceled, the average weekly frequency is around 1.5 times per week, showing a behavior quite similar to male users.</p><p><strong><em>2.14 — Correlation Chart</em></strong></p><p>Up to this point, an analysis has been conducted to determine the characteristics of users who have canceled their contracts. Despite all the information above, it’s still not possible to identify which characteristics have the most influence on cancellations. To address this, the Correlation Chart below will be plotted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*pXOhV_bLDInM0tPTYxcEPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*v0URm30Fl7e8ygVTi7TfRg.png" /><figcaption>Correlation chart plot</figcaption></figure><p>Above is the Correlation graph of all variables in the dataset. In the variable of interest (Churn), the correlation with the other variables is noted, where most values are negative, indicating an inverse proportional relationship between magnitudes. The variables with the highest negative values are: <strong><em>contract_period, age, month_end_contract, lifetime, </em></strong>and<strong><em> avg_freq_curr_month,</em></strong> all with values of -0.4. This suggests that the lower the value of these variables (for instance, the shorter the contract period or the fewer months remaining until the contract ends), the higher the chances of users canceling their plan.</p><h4><strong><em>2.15 — Preliminary Conclusion</em></strong></h4><p>Based on all the topics discussed above, where tables and graphs were generated with aggregated user information, it is possible to outline a preliminary typical profile of a user who might cancel the plan:</p><p><strong>1- GENDER MALE:</strong></p><ul><li>Age: 27 to 29 years old</li><li>Does not reside near the gym</li><li>Does not participate in any Partner Company program</li><li>Does not participate in the Friend Promotion</li><li>Does not provide a Phone Contact</li><li>Does not participate in Group Classes Contract Duration of up to 1 month</li><li>Up to 3 months until the end of the Contract</li><li>Up to 5 months of Service Utilization Time Spends an average of $100.00 monthly on various services (lower value than the average of other users)</li><li>Attended an average of 1 time per week in the last month (frequency lower than the average of other users)</li><li>Attended an average of 1.5 times per week throughout the period (frequency lower than the average of other users)</li></ul><p><strong>2 — GENDER FEMALE</strong></p><ul><li>Age: 25 to 27 years old</li><li>Does not reside near the gym</li><li>Does not participate in any Partner Company program</li><li>Does not participate in the Friend Promotion</li><li>Does not provide a Phone Contact Does not participate in Group Classes</li><li>Contract Duration of up to 1 month Up to 3 months until the end of the Contract</li><li>Up to 5 months of Service Utilization Time Spends slightly more than $100.00 monthly on various services (lower value than the average of other users)</li><li>Attended an average of 1.3 times per week in the last month (frequency lower than the average of other users)</li><li>Attended an average of less than 1.5 times per week throughout the period (frequency lower than the average of other users)</li></ul><h3>3 — Predicting customer churn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*YJ_XIwfPOjzLTDMcoMvI6A.png" /><figcaption>Reorder dataset</figcaption></figure><h4><strong><em>3.1 — The Logistic Regression Alghorithm</em></strong></h4><p>Logistic Regression algorithms are applied when there is some relationship between the data being analyzed. Classification attempts to predict which class or category it belongs to based on its characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*hf7jtFhxb6dS5wgk5cBqPA.png" /><figcaption>Separating the data into features (the matrix X) and the target variable (y)</figcaption></figure><p>As seen above in the dataset, some columns have magnitudes in the tens and hundreds. Therefore, the StandardScaler() method will be applied to rescale to compatible scales, ensuring that all columns have a mean of 0 and a standard deviation of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*6Qx96cE_h-hrNtlTnrHKIQ.png" /><figcaption>The average and standard deviation of the feature ‘avg_additional_charges_total.’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*zGPMtJzFOemwCH2CQ1vV2g.png" /><figcaption>Standardizing the data using the StandardScaler() method.</figcaption></figure><p>As seen above, the StandardScaler standardized the column values, such that the mean is close to 0 and the standard deviation equals 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*vxW-nSNxWbqio1xW-gNs2g.png" /><figcaption>Defining the algorithm to be applied.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*LDwfKBzjC19V1V9aTmG6SA.png" /><figcaption>Training the model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*BHq4gFFOYixOnTKNwARF6g.png" /><figcaption>Making prediction by model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Sv3nDB_P-MkZCOQjefEu5A.png" /><figcaption>Binary prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*vY7OBTrHydDLEvHdeZQ5Fg.png" /><figcaption>Plotting ROC Curve</figcaption></figure><p>The ROC curve (Receiver Operating Characteristic) is a graph of True Positive Rate (TPR) against False Positive Rate (FPR). It illustrates the relationship between sensitivity and specificity in a dataset, thereby determining the correct threshold value to be applied. This selection of the threshold is based on the trade-off between TPR and FPR, considering the nature and application of the problem. The red dashed line corresponds to a model that made random classifications. The further away the curve is from this reference line, the better the model’s classification. In the graph above, given the problem’s application and nature, the ROC_AUC value is 0.97, which is considered excellent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*qhVjQeUOUpC6NT2LtwuN-g.png" /><figcaption>Plotting all metrics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*k_d_liQAGYt8AhTL3Cl1WQ.png" /><figcaption>Plotting all coefficients</figcaption></figure><p>Above are tables with metrics for model performance, used to evaluate how well the model is making predictions.</p><ul><li><strong><em>Accuracy:</em></strong> measures the percentage of correct predictions made by the model out of the total number of instances ((TP + TN) / (Total Samples))</li><li><strong><em>Precision: </em></strong>measures the proportion of true positive predictions (TP) out of all positive predictions made by the model, indicating how many of the positive predictions were correct. It’s valuable when the cost of false positives (FP) is high. (TP / (TP + FP))</li><li><strong><em>Recall:</em></strong> measures the proportion of true positive predictions out of all actual positive instances in the dataset, indicating how well the model identifies positive instances. Recall is crucial when the cost of false negatives (FN) is high. (TP / (TP + FN))</li><li><strong><em>F1-score:</em></strong> harmonic mean between precision and recall, providing a balance between the metrics. (2*(precision * recall)/(precision + recall))</li></ul><p>Evaluating these performance metrics in the context of the project (predicting ‘churn’), here are some observations:</p><ul><li><strong><em>Accuracy</em></strong>: in predicting customer churn, this metric gives an overall view of the classifier’s correlation in predicting whether the customer will churn or not.</li><li><strong><em>Precision:</em></strong> important to avoid false positives and unnecessary retention efforts in customer groups where churn is not predicted.</li><li><strong><em>Recall:</em></strong> essential to ensure that most customers who will churn are correctly identified.</li><li><strong><em>F1-score:</em></strong> checks the balance of performance between customers who will churn and those who won’t.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*3OwuGbbbPOpStm3ZUeltiA.png" /><figcaption>Plotting Confusion Matrix</figcaption></figure><p>Above is plotted the confusion matrix, which summarizes the classification model’s performance by comparing predicted values with actual values:</p><ul><li><strong><em>TRUE NEGATIVE (TN):</em></strong> Instances correctly predicted as negative by the model (top-left corner — 574)</li><li><strong><em>FALSE POSITIVE (FP):</em></strong> Instances incorrectly predicted as positive by the model, i.e., when they are actually negative (top-right corner — 28)</li><li><strong><em>FALSE NEGATIVE (FN):</em></strong> Instances incorrectly predicted as negative by the model, i.e., when they are actually positive (bottom-left corner — 34)</li><li><strong><em>TRUE POSITIVE (TP):</em></strong> Instances correctly predicted as positive by the model (bottom-right corner — 164)</li></ul><h4><strong><em>3.1.1 — Changing Threshold</em></strong></h4><p>The default threshold value in the sklearn model is 0.5, meaning if the score is higher than this threshold, it predicts 1; otherwise, it predicts 0. One way to check if the threshold value is appropriate for the model is by adjusting this value and assessing the model’s performance and results. The threshold will be changed to 0.4, and the model’s performance will be evaluated accordingly.</p><p><strong><em>3.1.1.1 — Threshold below the default</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*V7u52LUwndf4yMalyhdVgw.png" /><figcaption>Changing the threshold.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*qlsUA5iTZien2XqjRRXLzQ.png" /><figcaption>Plotting all metrics and coefficients</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*DA-V9i8Jo3Py_QBCWRzdEQ.png" /><figcaption>Plotting ROC Curve</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*ZVAlVXvpjMwzMszV8myOnQ.png" /><figcaption>Plotting Confusion Matrix</figcaption></figure><p>The performance of the model with a threshold below the default value is shown above. It’s noticeable that there was a slight change in the values.</p><pre>                  limiar 0.5  - limiar 0.4<br> accuracy            0.85         0.82      - 3.58%<br> sensibility         0.83         0.85      - 2.41%<br> escore              0.84         0.83      - 1.20%</pre><p>As seen, there was an increase of 2.4% in the model’s sensitivity; however, there was a decline in the other values. There was also a decrease in the ROC values</p><p><strong><em>3.1.1.2 — Above the standard threshold</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*hvCS2xsVJiWcfNd-iTtL2g.png" /><figcaption>Changing the threshold.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*X0Ka7wvMokV50K7jZVLkFw.png" /><figcaption>Plotting all metrics and coefficients</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*tHiw0SYl4cqS4NbLoz5nSQ.png" /><figcaption>Plotting ROC Curve</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*JUO65aUV2p72E58iM9TSqw.png" /><figcaption>Plotting Confusion Matrix</figcaption></figure><p>Here is the performance of the model with a threshold above the default value. It’s noticeable that there was a slight change in the values</p><pre>                limiar 0.5  - limiar 0.4<br>accuracy            0.85         0.91    - 7.1%<br>sensibility         0.83         0.81    - 2.41%<br>escore              0.84         0.86    - 2.38%</pre><p>As observed, there was an increase of 7.1% in the model’s accuracy; however, there was a deterioration in the other metrics. ROC values also declined. It’s worth examining the business context here because an improvement in accuracy means avoiding false positives and unnecessary retention efforts for customer groups where cancellations are not predicted. Meanwhile, sensitivity (essential for correctly identifying most customers likely to cancel) and F1 score (evaluating the balance between customers likely to cancel and those who won’t) showed a decrease in performance</p><p><strong><em>3.1.2. — The Coefficients</em></strong></p><p>With the aim of improving the model’s performance and results, an analysis of the coefficients of the variables will be conducted to better understand the relationship between them and the project’s objective, which is to identify the factors influencing user cancellations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*5a4ohReYAnWh66Vu15I0ew.png" /><figcaption>New dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*qhXuVWRBPJzhfSSb8oUbyA.png" /><figcaption>Verifying the coefficients</figcaption></figure><p>As the StandardScaler method was applied to the model, continuous variables should be handled in terms of standard deviation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*QJ0dQszrhg9JQR_ZC7fJyw.png" /></figure><p>When working with binary variables (YES / NO), logarithmic functions are used to explain the results in terms of log-odds (odds ratio or likelihood of odds)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*eb1clmuAR47dqvlJiptQuw.png" /></figure><p>where p is the probability of the outcome occurring, in order to determine the corresponding log-odds of the outcome, which is then modeled with a linear combination of the explanatory variables. Thus, the model coefficients can then be interpreted to understand the direction and strength of the relationships between the explanatory variables and the response variable.</p><p>Assuming there is no multicollinearity between the variables, meaning the variables are independent of each other, the variables will be analyzed in the context of the proposed business:</p><ul><li>For binary variables, checking the correlation matrix, let’s take the example of the variable <strong><em>‘group_visits’</em></strong> (group classes). Keeping all other variables fixed and applying exp^(-0.719085) = 0.4871, this means that the likelihood of cancellation for a user who attended group classes is 0.48 times lower than users who did not participate in group classes.</li><li>For numerical variables, as they were scaled using the StandardScaler method, they should be analyzed in terms of standard deviation. Keeping all other variables fixed, let’s take the example of the <strong><em>‘lifetime’</em></strong> variable (service usage time). We have that exp^(-0.534026) = 0.5862, meaning that an increase of one unit of standard deviation in lifetime reduces the cancellation chances by 0.58 times.</li></ul><h4><strong><em>3.2 — Applying the Random Forest Classifier Algorithm</em></strong></h4><p>RandomForest method consists of multiple decision trees, where each tree produces a prediction. When performing a classification task, each decision tree in the method ‘votes’ for one of the classes related to the input. Once all the trees reach a conclusion, the method will count which class received the most votes, and that class will be what the method produces as a prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Zg2pA-TwfknqoI9GUdXWFA.png" /><figcaption>RamdomForest algorithm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*dR0VH5O0fxAMj4LFyYOd3g.png" /><figcaption>Making predictions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*RO9s9cC2JSi3yDFDhOtGaA.png" /><figcaption>Plotting ROC Curve</figcaption></figure><p>A Receiver Operating Characteristic (ROC) curve is a graph of the True Positive Rate (TPR) against the False Positive Rate (FPR). It demonstrates the relationship between sensitivity and specificity in the dataset, thus determining the correct threshold value to be applied. This selection of the threshold to be chosen is based on the trade-off between TPR and FPR, considering the nature and application of the problem. The red dashed line corresponds to a model that made random classifications. The farther the curve is from this reference, the better the model’s classification. In the graph above, given the application and nature of the problem, the ROC_AUC value = 0.9679, considered excellent</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*11dq8G7zGaA9_mfA66rWtA.png" /><figcaption>Plotting the metrics</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*pGURpzDeDPS3xRQsh_bYaw.png" /><figcaption>Verifying the coefficients</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*az6TDyhTbYIHyvMxACApGw.png" /><figcaption>Plotting Confusion Matrix</figcaption></figure><p>Above is the table with the model’s performance as well as the confusion matrix. Comparing the values with the <strong>LogisticRegression</strong> method with a threshold = 0.5 (default), one can observe:</p><pre>              Log.Regression  - R.Forester<br>accuracy            0.85           0.84    - 1.20%<br>sensibility         0.83           0.82    - 1.20%<br>escore              0.84           0.83    - 1.20%</pre><p>As seen, there was a 1% degradation when comparing the performance of the two models. There was also a decrease in the ROC values (0.13%). It’s worth noting that the <strong>RandomForest</strong> algorithm was applied in its ‘default’ mode. It might be interesting at another time to explore the additional functionalities and adjustments of the algorithm in order to better fit the proposed business model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*rmwpe-hPP_TduX6DcwPnIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*a2ZJjvMLkPaBO1xZtxm7Bg.png" /><figcaption>Plotting the random tree of the dataset</figcaption></figure><p>Above is an overview of the arrangement of variables in the <strong>RandomForest</strong> algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*FUlW0JcSokjsyt7P6cTifQ.png" /><figcaption>Ordering the variables</figcaption></figure><p>Above is a table generated of the variables in order of importance by the algorithm, meaning, among all variables, which ones the algorithm considers the most during prediction or which variables are most accessed by each individual tree. Here, it’s worth delving deeper into this hierarchy generated by the model and the target variable, namely, if this ranking is related to a higher probability of user churn or not.</p><h3>4 — User Clustering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*LtqUl0qC_8c7R1o0Lhuk-w.png" /><figcaption>Standarizing the dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*6jL3vXQuEdoe8mb3PPkfeg.png" /><figcaption>Applying the K-means algorithm</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*B3rfj6mkAKS6UD5DWJMRCA.png" /><figcaption>Plotting the dendogram</figcaption></figure><p>Above, the dendrogram of the dataset clustered by the clusters generated by the K-Means clustering algorithm was plotted. For an overview, the dendrogram is useful, but a more detailed view of the clusters isn’t possible. Therefore, separate clusters will be plotted for a better visualization and analysis of the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*O4GoT3mQfw9Kbf-QLFtNSw.png" /><figcaption>Plotting the clusters separated</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*lAWYSJVCJpl1FezL54qrNA.png" /></figure><p>Above, it’s noticeable through the plotted graphs of the separate clusters the arrangement of variables in each cluster.</p><ul><li><strong>Cluster 0:</strong> the variable with the most negative value (influence) is <strong><em>‘near_location’ </em></strong>(users living close to the gym), which stands out from the other variables. It’s also noticeable that almost all variables are negative, and only <strong><em>‘churn’</em></strong> is positive, indicating the possibility of inversely proportional variables. That is, the lower the variables, the higher the chance of user cancellation, confirming what was mentioned in topic 2 with the correlation matrix.</li><li><strong>Cluster 1:</strong> here, the opposite of cluster 0 is observed, where all variables are positive, and the ‘churn’ variable (cancellation) is negative. Thus, the higher these variables, the lower the chance of cancellation. It’s evident that the algorithm attributed a higher value to <strong><em>‘contract_period,’ ‘month_to_end_contract,’ ‘avg_class_freq_total,’ </em></strong><em>and</em><strong><em> ‘avg_class_freq_month’</em></strong> as the variables with the most influence on a user not canceling.</li><li><strong>Cluster 2:</strong> here, the algorithm identified the scenario with the highest chance of cancellation: all variables are negative, indicating users with the worst profile for the gym.</li><li><strong>Cluster 3 and Cluster 4:</strong> these are users with similar profiles, but with some differences. For example, in Cluster 3, even though the user has a short contract (‘contract_period’) and only a few months left on the contract (<strong><em>‘month_to_end_contract’</em></strong>), the chances of cancellation for this user are low. The same applies to Cluster 4, where there’s a user with a low weekly frequency for the month (<strong><em>‘avg_class_freq_month’</em></strong>) and low total weekly frequency (<strong><em>‘avg_class_freq_total’</em></strong>). The chances of cancellation for these users are low.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*RC-U_RzZH2_m3mLBp0q0yw.png" /><figcaption>Plotting the clusters grouped 2D method</figcaption></figure><p>Above, the cluster grouping graph of users was plotted to visually understand the clustering of clusters and users. For a better understanding, the dataset was reduced to 2D using the PCA method</p><h3><strong><em>5 — Conclusion</em></strong></h3><p>With this, here are some recommendations to increase user retention at the gym:</p><ul><li>Maximize the sale of contracts with durations longer than 6 months, offering discounts or promotions on other available classes.</li><li>Encourage higher weekly attendance from users by implementing some form of reward or discount for regularity.</li><li>Encourage users to provide their complete data at the contract signing (ensuring their full commitment in compliance with GDPL). Organize outdoor classes (in parks or squares) to boost engagement through group sessions.</li><li>Run promotions targeting specific age groups and genders to attract the 18 to 22-year-old demographic, where the cancellation rate is proportionally lower.</li></ul><p>If you have any doubts or suggestions, please don’t hesitate to contact me! Thank you very much for reading!</p><p>Connections:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64a489c994f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation: Understanding Your Most Valuable Customers!]]></title>
            <link>https://medium.com/@alanjpr/segmenta%C3%A7%C3%A3o-de-clientes-conhecendo-seus-clientes-mais-valiosos-50ed31010dff?source=rss-2c8ee671d68a------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ed31010dff</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[e-commerce-business]]></category>
            <dc:creator><![CDATA[Alan Paz Ribeiro]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 19:15:38 GMT</pubDate>
            <atom:updated>2023-12-04T13:34:51.739Z</atom:updated>
            <content:encoded><![CDATA[<p>Building an RFM Analysis Model and K-means Clustering for Customer Segmentation in Retail E-commerce</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*szVQemuqVEfa-2W3zZhZow.jpeg" /></figure><p>Hello, everyone!</p><p>I’m going to share a customer segmentation project here applying three segmentation techniques: cohort analysis, RFM analysis, and K-means clustering.</p><p>Each customer is unique, and thus, a one-size-fits-all approach isn’t effective. Customer segmentation is a crucial strategy to better understand the individual needs of each customer. Segmentation involves grouping customers with similar characteristics.</p><p>By doing so, we gain a better understanding of their needs and purchasing behaviors, enabling the marketing and sales team to adapt strategies to better serve each customer. But why is customer segmentation important? Here are a few points:</p><p>1- Improved Customer Relationship and Brand Loyalty: Customer segmentation highlights what each customer needs, allowing marketing and sales teams to best tailor their communication. It reveals interests, shopping habits, and even budget, showing the customer that they are valued.</p><p>2- Optimizes Time and Resources: By knowing in advance the right way to engage with customers, the marketing team can better direct their campaigns more accurately.</p><p><strong>Project Objective</strong></p><p>User segmentation based on their consumer profile in order to gain business insights.</p><p><strong>About the Data:</strong></p><p>The raw data was provided in the form of a <a href="https://github.com/alanpazribeiro/Segmentacao_clientes_RFM_Kmeas/blob/main/Parte%203%20-%20Dataset.rar"><em>CSV file</em></a> with 541,000 rows of data, a dataset from an online retail store with all transactions made between 29–11–2018 and 07–12–2019 will be used. The site sells all kinds of items, primarily catering to wholesale trade.</p><h3><strong><em>1 — Introduction</em></strong></h3><p>After a detailed Exploratory Data Analysis (EDA) on the dataset to check data consistency, including verifying null/missing data, missing data in some columns, negative data, correcting column names, and data type conversion, we arrive at the dataset below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmfRV2IenXto8I-yECJjWw.png" /><figcaption>Dataset after EDA</figcaption></figure><h3><strong><em>2 — Analysing the Data</em></strong></h3><p><strong><em>2.1- </em></strong>Analysis of the <strong><em>‘customer_id’</em></strong> and <strong><em>‘invoice_id’</em></strong> columns</p><p>The <strong><em>‘customer_id’ </em></strong>and <strong><em>‘invoice_id’</em></strong> columns will be analyzed to check the distribution of the quantity of items purchased per user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*Z6B83AhKKmMqqk2nnC7XdA.png" /><figcaption>Groupby tables ‘customer_id’ and ‘invoice_id’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJ7GzeFqG42HqWDRAyIfbQ.png" /><figcaption>Graph of unique numbers orders of users</figcaption></figure><p>Above, we have the distribution of users <strong><em>(‘customer_id’)</em></strong>. Now, focusing on the unique numbers of orders <strong><em>(‘invoice_id’)</em></strong>. Some observations from the graphs:</p><ul><li>1x is the smallest number of times a user made a purchase.</li><li>248x is the largest number of times a user made a purchase.</li><li>25% of users made up to 1 purchase.</li><li>50% of users made up to 3 purchases.</li><li>75% of users made purchases up to 5 times.</li><li>The average is 5 purchases per user.</li></ul><h4><strong><em>2.2 — </em></strong>Temporal Analysis of Columns (columns ‘date’, ‘month’, ‘hour’)</h4><p>We will now analyze the temporal relationship between the<strong><em> ‘customer_id’</em></strong> (user) and <strong><em>‘invoice_no’ </em></strong>(invoice number) columns, in other words, how many products each consumer purchased over time, per day, in the monthly aggregate, and by hour.</p><p><strong><em>1 — Date</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*Vy1tSaOD8i-FcOEPE8wfRg.png" /><figcaption>Grouping table by date</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z7y7Qr920i4mtSVXAdyy7A.png" /><figcaption>Graph of the distribution of items purchased by date</figcaption></figure><p>Based on the grouped columns<strong><em> ‘date’, ‘invoice_no’</em></strong> and <strong><em>‘customer_id’ </em></strong>to examine the distribution of items purchased per <strong><em>‘customer_id’</em></strong> user over the analyzed period. It’s noted from the graph that:</p><ul><li>The smallest daily purchase is 1 item.</li><li>The largest daily purchase is 543 items.</li><li>25% of users bought up to 5 items per day.</li><li>50% of users bought up to 14 items per day.</li><li>75% of users bought up to 27 items per day.</li><li>The average is 20 items per user per day.</li></ul><p><strong><em>2 — Day</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*O3j4XXTBtXx9jz84xwwtEw.png" /><figcaption>Table of distribution by items purchased</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_bDysOpTgD7bAyMXMCNGQ.png" /><figcaption>Graph of the monthly distribution of items purchased</figcaption></figure><p>According to the above graphs showing the unique sum of daily purchases per user. The intention here is to verify how many times each user made a purchase per day. Considering that each purchase generates a different <strong><em>‘invoice_no’</em></strong> (invoice number), applying the<strong><em> .nunique()</em></strong> method to this column yields the number of purchases (accesses) for each user per day. It’s observed from the statistical description of the data in the table above and from the graph that about 75% of users accessed at least once a day, and the maximum number of accesses per day is 24.</p><p><strong><em>3 — Month</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*rUp7wYyK2ioEfgAORy1PEg.png" /><figcaption>Table of grouping by month and unique number of orders</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*dXqJSZ4z5OtlmdITk8IjGQ.png" /><figcaption>Graph of the unique quantity of orders</figcaption></figure><p>Taking into account that each record of<strong><em> ‘invoice_no’</em></strong> corresponds to an item purchased by a user, the table and graph above are plotted. It’s noticeable that there’s an increasing trend with alternation between the months, meaning, months 1, 3, and 5 show growth compared to the previous months (2 and 4). Months 6, 7, and 8 show very close values, and from there, the following months exhibit a significant increase in items purchased, reaching the maximum peak in 11; then experiencing a decline in 12. Another interesting fact is that months 9, 10, and 11 together account for 35% of the total items purchased in the period compared to the other months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*jMcf2HYFLhgWuXdnCQ_tpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*cfsM-K8h5KJQLawJ3HA1kg.png" /><figcaption>Graph of the unique quantity of orders per day</figcaption></figure><p>Continuing with the same approach as above, here are the unique purchases grouped by day. There’s an increasing behavior in the first 4 days, reaching the maximum peak on the 4th day. Following that, there’s a decreasing trend extending until the 31st day, indicating a higher user preference to shop in the first two weeks of the month, especially on days 4 and 12:</p><ul><li>1st week: 25.9%</li><li>2nd week: 23.6%</li><li>3rd week: 22.7%</li><li>4th week: 19.6%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*1ab-GVYMjTrf4ZFpE0TRqQ.png" /><figcaption>Table of grouping by hour and calculating the unique number of orders</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*iJP2s6dmnte2ToA-XvR5yA.png" /><figcaption>Graph of the quantity of unique orders per hour</figcaption></figure><p>Above, we have the unique purchases, now grouped by hour. It’s possible to observe that site visits and purchases made are not homogeneous throughout the hours. Approximately 67% of all purchases are made between 10 AM and 2 PM (with the peak at 12 PM), as per the table above, indicating the preferred time for users to access the site and consequently make purchases.</p><h4><strong>2.3 — </strong>Analysis of ‘customer_id’ and ‘total_price’ columns</h4><p>We’ll now analyze the relationship between users <strong><em>(‘customer_id’)</em></strong> and the total price of items purchased <strong><em>(‘total_price’)</em></strong>, i.e., how much each user spent per date and aggregated day, month, and hour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*ItAk_otTR11Qql-YwN8iRA.png" /><figcaption>Monthly grouping table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*n-t52l_XW2hleurkiImmUQ.png" /><figcaption>Graph of total purchase value per month</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*lnymhLE7ImADzH4wJmY6nw.png" /><figcaption>Daily purchase grouping table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*DQslXkmIrGgUYUJBsYUAtw.png" /><figcaption>Graph of total purchase value per day</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*i4q72cHhX4JAK7sHxCRs3w.png" /><figcaption>Hourly purchase grouping table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*UZwwjsPMmqvdaMp6t524sQ.png" /><figcaption>Graph of total purchase value per hour</figcaption></figure><p>From the tables and graphs above, some important observations can be pointed out:</p><ul><li>On average, each user bought 92 different items during the period.</li><li>On average, each user visited the site 5 times to make a purchase during the period.</li><li>On average, each user bought about 20 different items per day.</li><li>Approximately 75% of users access the site at least once a day.</li><li>35% of the total items in the period were purchased in months 9, 10, and 11.</li><li>Days 4, 5, and 6 are the days with the highest number of purchases in the period, with the first week accounting for almost 26% of the total.</li><li>About 66% of purchases recorded during the period occur between 10 am and 2 pm.</li><li>Not always days with the highest number of accesses are responsible for the highest revenue; in other words, revenue is not only related to the number of users accessing the site but also to the value of items purchased on the same day/month.</li></ul><h3><strong>3— </strong>Customer Segmentation</h3><p>Customer segmentation involves grouping existing and potential customers based on shared characteristics. By segmenting customers into different classes, it becomes possible to better understand their needs, preferences, and buying patterns.</p><p>It’s a crucial tool for decision-making or necessary action to increase revenue, build a good customer relationship, and optimize sales and marketing campaigns. Its benefits include:</p><ul><li>Greater customer relationship and brand loyalty: Customer segmentation gives us a reference to take actions for each customer in their segment, such as product differentiation, focusing campaigns for each customer, and other strategies we might have;</li><li>Resource optimization: Customer segmentation has enabled companies to prioritize scale. This segmentation allows us to reach the “star” customer with significant purchases up to the “rare” customer with low purchases. Companies can focus their energy, costs, and attention on that specific segment.</li></ul><h4>3.1 — Cohort Analysis</h4><p>Cohort analysis is different from other customer segmentation techniques because it analyzes them temporally, meaning it analyzes customer behavior within a period of time and within defined time frames (semesters, quarters, months, weeks, etc.) to check for changes in customer behavior over time. For the purposes of the study, the following metrics will be analyzed:</p><ul><li><strong>Active Users:</strong> the percentage of customers who return to make purchases on the site;</li><li><strong>Quantity of Orders:</strong> variation in the number of orders;</li><li><strong>Purchase Frequency:</strong> how many times (on average) per month customers buy;</li><li><strong>Average Revenue Value:</strong> variation in average revenue over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*V3xxeKX9Eb5jc9g1td6_-Q.png" /><figcaption>Reference dataset</figcaption></figure><p>As the analysis will be done over a period of 1 year, some lines outside this date range will be excluded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*1NPJtUadPmw0GJhR9lQxgg.png" /><figcaption>Minimum and maximum dates</figcaption></figure><h4><strong>3.1.1 — </strong>Minimum and maximum dates-Retention</h4><p>Grouping users and summing the <strong><em>‘total_price’</em></strong> column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*J-jXh98RjRhZ-hILMVZgdA.png" /><figcaption>Table grouping by users and sum of total purchase values</figcaption></figure><p>Grouping users by minimum date:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*wt4x0GVVF47MJ3nGun0KjA.png" /><figcaption>Table of users by date</figcaption></figure><p>Joining the two tables by user and adjusting the date and time columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jjWKmiQQo6N8eATJKKYjQ.png" /><figcaption>Aggregating the tables</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEjJ2WAgUlvXeFndHN5aFA.png" /><figcaption>Changing column data</figcaption></figure><p>Criando a coluna <strong><em>‘cohort_lifetime’:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5IgbGyuNNxsbMYkKsNGWg.png" /><figcaption>Column dataset ‘cohort_lifetime’</figcaption></figure><p>Creating the<strong><em> ‘cohort_lifetime’ </em></strong>column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6yC9lDz4b4HlS4KMkpNdQ.png" /><figcaption>Table grouping by ‘cohort_lifetime’</figcaption></figure><p>It’s possible to observe user behavior on the site within the analyzed period. <strong><em>‘Cohort_0’</em></strong> indicates all customers who accessed and made a purchase. <strong><em>‘Cohort_1’</em></strong> shows how many of these users made a purchase again in the following month. <strong><em>‘Cohort_2’</em></strong> shows how many bought months after the first purchase, and so on. Calculating the percentages from the table above, it can be observed that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwddSn-EchTo98_JOLfagg.png" /><figcaption>Cohort percentage table</figcaption></figure><p>Calculating the Overall Average of the number of users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVMQelBE5MpsLlLGerXttg.png" /><figcaption>Average number of users</figcaption></figure><p>Plotting the Users Cohort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awvVxTgVnF6-ut5nr364Kg.png" /><figcaption>Cohort Heatmap</figcaption></figure><p>Analyzing the tables and graphs above, the percentage distribution of user access over the period is noted. In the first row, it is observed that 316 users returned to buy after having made a purchase for the first time in the previous month, which corresponds to 41% of users who returned to the site. The higher this percentage, the greater the acceptance of the store’s site products and the higher the retention rate of these users. Approximately 55% of users return to the site after 1 year, according to cohort 11.</p><p>It is also observed that the overall average rate of user access throughout the period (2018–2019), which shows a value of approximately 21%. Upon analyzing the graph, it is noticeable that older users show a higher retention rate, possibly impacted by the larger amount of observable data from these users compared to others. Analyzing by date, it is observed that these users also show a higher average rate, about 39%.</p><h4><strong>3.1.2 —</strong>Quantity of Orders in the Period</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73lLgpK-97VmjaEyuH2_jw.png" /><figcaption>Orders Quantity Cohort</figcaption></figure><p>Calculating the average from the above table, it can be seen that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yiN80pVzMs67ADEjgdVO5A.png" /><figcaption>Percentage of orders quantity</figcaption></figure><p>Plotting the quantity of orders Cohort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9vzZMulFLPdKyGs6xAfmLg.png" /><figcaption>Cohort Heatmap</figcaption></figure><p>From the tables and graphs above, the behavior of users regarding the quantity of orders placed is noted. Checking the cohorts horizontally (customer lifetime), it is noted when users are returning to the site. In the last column, the average rate of products purchased is observed, where from month 3 there is a decrease of almost 20% between months, reaching 21%, which remains until month 11.</p><p>Analyzing the cohorts vertically (site lifetime or product lifespan — demonstrating the site/product’s relevance over time), it is observed that there is a stagnation at about 20%-25% in the quantity of orders placed from the third month in most cohorts. An interesting fact is that all cohorts show a significant increase (or a value close to the previous cohort) in the penultimate month, subsequently dropping dramatically in the following month.</p><h4><strong>3.1.3 — </strong>Purchase Frequency in the Period</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W76OAo2Fdqa2NOO_I2YQwQ.png" /><figcaption>Purchase Frequency Cohort</figcaption></figure><p>Plotting the Purchase Frequency Cohort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydo5UfvHRNS5FrLn0a9HpQ.png" /><figcaption>Cohort Heatmap</figcaption></figure><p>Above are the table and graphs that indicate the relationship between the number of orders and the number of users in the period. It is noted that the ratio of orders per customer is positive, where each customer would be generating more than one order per month. It’s interesting that in the first cohort, for each user, almost 2 orders were placed on average. In cohort 11, the value of orders per user exceeded the average, with more orders.</p><h4><strong>3.1.4 — </strong>Average and Total Revenue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hj0pfqUU8Nc6yCPcAvmdHw.png" /><figcaption>Average Revenue Cohort</figcaption></figure><p>Calculating the Average of the Cohort above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDvnxSnbMH8VDj0Mcz-WNQ.png" /><figcaption>Percentage of Average Revenue Cohort</figcaption></figure><p>Plotting the Average Purchase Cohort:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54qjhfC_YjPoNFXKlXDFEA.png" /><figcaption>Cohort Heatmap</figcaption></figure><p>According to the tables and graphs plotted above, the behavior of the site’s revenue generated by users over the period is noted. Comparing it with the Quantity of Orders Graph and Purchase Frequency Graph of Users, a proportionality between them is noted, meaning that in certain months, not only does frequency decrease but also the quantity of products, and consequently, revenue is impacted.</p><p>An interesting point to note is that the months of OCTOBER and NOVEMBER have the greatest positive impact on the site’s revenues, which is verified in all cohorts. Taking as an example a user who made their first purchase in ‘2019–08–01’, about 58% of users return to the site in OCTOBER (cohort 2) and 68% in NOVEMBER (cohort 3), where the user flow begins to increase from the month of SEPTEMBER, as seen in the above graph.</p><h3><strong>3.2 — </strong>RFM Analysis</h3><p>Among the various Customer Segmentation models, the RFM model is probably the most used in customer behavior analysis. It consists of segmenting the customer base into homogeneous groups to better understand their characteristics and direct more assertive campaigns. The RFM model <strong><em>(Recency, Frequency, and Monetary Value)</em></strong> is based on customer behavior, analyzing their transaction history — how frequent or recent their purchases were. The RFM model also helps group customers into clusters to identify which ones are most likely to respond to marketing campaigns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*TUbDzgkU3auQf1jk1Dlx5g.png" /><figcaption>Dataset</figcaption></figure><p>Grouping by user and dates of most recent purchases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*COFkaIk0_2DvyXw9OfYebA.png" /><figcaption>Table of user grouping and revenue</figcaption></figure><p>Setting reference time and renaming columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*hx_7elhlvhRPgkRvNCMbjA.png" /><figcaption>Reference time table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*FeECDqQePrqQ5VuTJt1BjQ.png" /><figcaption>Renaming columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*E7kaKSpnapa2ZUrNgT56lA.png" /><figcaption>RFM Graphs</figcaption></figure><p>From the plotted graphs above, there’s a significant number of outlier values in both graphs, except in the ‘recency’ variable, suggesting the need for proper handling so that the RFM analysis isn’t influenced by these values.</p><h4><strong>3.2.1 — Outliers</strong></h4><p>To verify the outlier values of the variables, the <strong><em>Z-SCORE </em></strong>method will be applied, indicating how far a given point is from the mean. For example, a z-score of 3 indicates a value is 3 standard deviations away from the variable’s mean.</p><p>Removing the <strong><em>‘customer_id’</em></strong> column and reorganizing the index</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*zzxKk94pn4eRaZrC2Uhz9g.png" /><figcaption>Index reorganization table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*G5iFAptE_0dPcw-4qLa3XQ.png" /><figcaption>Summary statistics table</figcaption></figure><p>From the above statistical summary, it’s noted that extreme values of the columns have been excluded.</p><h4><strong>3.2.2- </strong>Grouping R-F-M Characteristics</h4><p>There are several ways to calculate RFM scores for RFM variables. The most used way is to assign scores based on quintiles from 1 to 5 with equal grouping sizes for each. The advantage of this method is its ease of application and understanding for marketing personnel. However, dataset skewness could lead to issues in the final results. To convert RFM variables into scores, the <strong><em>qcut()</em></strong> function will be used to divide the dataset into equal parts (in this case, 5 parts).</p><p>As the <strong><em>qcut() </em></strong>function groups with uneven compartment sizes but equal sample counts in each group, the initial and final arguments, as well as the period, will be passed. For the ‘recency’ column, a lower value means a more recent date (user return to the platform) and hence should have a higher value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*kTHeBDnRaZXkSqvCw7oHCg.png" /><figcaption>Recency calculation table</figcaption></figure><p>For the <strong><em>‘frequency’</em></strong> column, there might be cases where, due to a value appearing many times, it falls into multiple intervals (users who made only 1 purchase, for instance). Therefore, the rank(method=’first’) method will be used, where the first occurrence found is assigned as the value for the respective interval, reducing the occurrence of the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*bZXXaEpi_G9RBXxIjvGNLA.png" /><figcaption>Frequency calculation table</figcaption></figure><p>The same procedure will be applied to the <strong><em>‘monetary’</em></strong> column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*s3yvfH4oktRR24dRTBQh-Q.png" /><figcaption>Monetary calculation table</figcaption></figure><p>Concatenating the <strong><em>‘r_score’, ‘f_score’</em></strong> and <strong><em>‘m_score’ </em></strong>columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*gjvzgo0V9FpyqQxkVD5O5w.png" /><figcaption>Concatenating the columns</figcaption></figure><h4>3.2.3 — Labeling the Data</h4><p>According to literature, there are several ways to label RFM segments, from the more complex with multiple labels for segmentations to simpler ones that try to minimize the number of segments. In this analysis, a segmentation containing labels: <strong><em>‘Star’ — ‘Loyal’ — ‘Potential Loyal’ — ‘Hold and Improve’ — ‘Risky’ </em></strong>will be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*2686X6Y79W6244R6WdYaTQ.png" /><figcaption>Columns label table</figcaption></figure><p>Grouping by segment and counting users:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*eEfCaoIb7GGE0YfvQydHLQ.png" /><figcaption>Segment grouping by name and users</figcaption></figure><p>From the table above, where it was grouped by segment and checked the <strong>rfm_min</strong> and <strong>rfm_max</strong> values, it’s noted the distribution of the number of users in each segment. The <strong><em>‘Loyal’</em></strong> segment appears first with the highest number of users, although presenting median rfm values. Interestingly, even though the ‘Risky’ segment has the third-highest number of users, its rfm values are the worst.</p><p>Grouping by segment and minimum and maximum scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*Xti0tQ2fZJseGnOjsnXHIg.png" /><figcaption>Segment grouping table by segment name</figcaption></figure><p>Grouping by segment and average scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*ecw7e60CDYoGt9Hv3IwlnQ.png" /><figcaption>Segment grouping table by segment name and scores</figcaption></figure><p>From the values in the tables above, the distribution of rfm values is noted. Some important points are worth mentioning:</p><ul><li><strong>Recency</strong>: The <strong>‘Loyal’</strong> and <strong><em>‘Star’</em></strong> segments have equal minimum recency values (on average, <strong><em>‘Loyal’ </em></strong>has over double the days), and <strong><em>‘Risky’</em></strong> presents the worst values with an average of 263 days since the users’ last purchase.</li><li><strong>Frequency:</strong> The <strong><em>‘Star’</em></strong> segment presents a minimum frequency (purchase frequency) much higher than the others (56 against 1), as well as the maximum frequency (721). Interestingly, the <strong><em>‘Hold and Improve’</em></strong> segment shows double the maximum frequency of <strong><em>‘Potential loyal’,</em></strong> even presenting a higher average value. The <strong><em>‘Risky’</em></strong> segment again presents the worst numbers, showing a very low average purchase frequency for the period.</li><li><strong>Monetary:</strong> The <strong><em>‘Loyal’</em></strong> and <strong><em>‘Star’</em></strong> segments have similar maximum values, as well as <strong><em>‘Potential loyal’</em></strong> and <strong><em>‘Hold and improve’</em></strong>; however, their minimum values are very distant from each other (as verified by the mean).</li></ul><h4><strong><em>3.3 — </em></strong>K-means Segment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*4GDrQt_RZ8Au-P0figvN0w.png" /><figcaption>Dataset</figcaption></figure><p>As the values of <strong><em>‘Recency,’ ‘Frequency,’ </em></strong>and <strong><em>‘Monetary’ </em></strong>present significantly different magnitudes (especially <strong><em>‘Monetary’</em></strong>), it is necessary to apply the <strong>StandardScaler</strong> method so that the K-means algorithm does not overweight this variable at the expense of others, avoiding distortions in the analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*tmBupg7Afib1Eq_ym5chzw.png" /><figcaption>Data Standardization Table</figcaption></figure><p>Before applying the K-means algorithm, it’s necessary to choose the number of clusters optimally. The Elbow method will be used to find the number of clusters suitable for the dataset.</p><p>Adjusting K-means from 1 to 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*eF4yWzoC-BBKoPZ0NdEYYA.png" /><figcaption>Dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*h-mJhQYP7V0OQHZYXRbNvw.png" /><figcaption>Elbow curve</figcaption></figure><p>By observing the graph’s behavior, it’s noticeable that values of 3 and 4 are potential due to the curve’s inclinations before and after these points. Hence, the value 4 will be selected.</p><p>Applying the K-means algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*Tb08q5njq_6M8jmIEbt2GA.png" /><figcaption>K-means algorithm:</figcaption></figure><p>Clustered dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*i6d7ZxJpDJO20vRIsrKGbw.png" /><figcaption>Tabela dos dados clusterizados</figcaption></figure><p>Non-standardized dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*xPI5ud9fZ0N4KC8SdjepsA.png" /><figcaption>Non-standardized dataset:</figcaption></figure><p>Grouping by segment name and calculating the users and their scores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*qLgySXBVB_pbfxbXnV_smQ.png" /><figcaption>Segment Grouping Table</figcaption></figure><p>Grouping by cluster and calculating the minimum and maximum scores of <strong><em>‘Recency,’ ‘Frequency,’ </em></strong>and <strong><em>‘Monetary’</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CDOpqWUtDUp7Q-PBolj3yA.png" /><figcaption>Cluster Grouping Table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*smNMH20FEELnQImZxcHRQg.png" /><figcaption>Tables of cluster groups and scores:</figcaption></figure><p>Plotting the clusters separately by segment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*dYUT47APoaCiaop81azioQ.png" /><figcaption>Cluster Graphs</figcaption></figure><p>From the plotted graph above referring to the clusters, it can be inferred that:</p><ul><li><strong>Cluster 0:</strong> Equivalent to the ‘<strong><em>Loyal</em></strong>’ segment. They exhibit similar characteristics to Cluster 2 users, with low recency and high frequency, but with low financial return (likely these users buy a lot and frequently low-value-added items);</li><li><strong>Cluster 1:</strong> It’s the worst segment, presenting the highest recency value (interval between purchases) and also shows low purchase frequency (about 25 purchases/day on average). It also has the lowest monetary value and the second-highest number of users. Equivalent to the ‘<strong><em>Risky</em></strong>’ group from RFM. It has around 1014 users (second-largest group);</li><li><strong>Cluster 2:</strong> The main user segment (equivalent to the ‘<strong><em>Star</em></strong>’ group from RFM). They are regular and current buyers (low recency and high frequency) as well as the most profitable, showing the highest ‘monetary’ value among the groups. According to Table 78, there are only 86 of them (about 3% of total users). Their most recent transaction was 16 days ago;</li><li><strong>Cluster 3:</strong> A segment that presents behavior combining ‘<strong><em>Potential loyal’</em></strong> and <strong><em>‘Hold and improve’,</em></strong> where they show regular recency and frequency. It has the highest number of users, with around 2624, and an average purchase frequency of 45 purchases/day.</li></ul><h3><strong>4 — Conclusion</strong></h3><p>The aim of the project is the segmentation of users based on their consumer profile and a subsequent analysis of the results.</p><p>In <strong><em>Chapter 2</em></strong>, the datasets were examined for:</p><ul><li>Missing and duplicate values</li><li>Data description</li><li>General information</li><li>Items with a value of 0</li><li>Items with negative value</li><li>Column renaming</li></ul><p><strong><em>Chapter 3</em></strong> involved the analysis of the entire dataset, covering topics such as:</p><ul><li>Distribution of users by diversity of purchased items</li><li>Daily distribution of items per user</li><li>Quantity of unique items per month, day, and hour</li><li>Total purchase value per month, day, and hour</li></ul><p>In<strong><em> Chapter 4</em></strong>, Customer Segmentation was performed to group users based on common characteristics. Two types of segmentation were adopted:</p><ul><li>Temporal segmentation, applying Cohort Analysis, to examine user behavior over time.</li><li>Behavioral segmentation, applying RFM Segmentation and K-means clustering, to group users with similar behaviors and thus promote more assertive campaigns.</li></ul><p>Cohort Analysis examined metrics such as:</p><ul><li>Active Users: percentage of customers returning to make purchases on the site</li><li>Quantity of Orders: variation in the quantity of orders</li><li>Purchase Frequency: average monthly frequency of customer purchases</li><li>Average Revenue: variation in the average revenue over the period</li></ul><p>In the RFM Analysis <strong><em>(Recency, Frequency, Monetary)</em></strong>, a scoring method based on quintiles of 1 to 5 was adopted, considering groups of equal sizes. Looking at the values in the tables above, the distribution of RFM values is evident. Some important points to highlight include:</p><ul><li><strong><em>Recency</em></strong>: The <strong><em>‘Loyal’ </em></strong>and <strong><em>‘Star’</em></strong> segments show equal minimum recency values (on average, <strong><em>‘Loyal’</em></strong> has more than double the days), while <strong><em>‘Risky’</em></strong> presents the worst values with an average of 263 days since the users’ last purchase.</li><li><strong><em>Frequency</em></strong>: The ‘<strong><em>Star</em></strong>’ segment presents a minimum frequency (purchase frequency) well above the others (56 versus 1) as well as the maximum frequency (721). It’s interesting to note that the <strong><em>‘Hold and improve’</em></strong> segment shows double the maximum frequency of <strong><em>‘Potential loyal,’</em></strong> even presenting a higher average value. Once again, the ‘Risky’ segment shows the worst numbers, with a very low average purchase frequency for the period.</li><li><strong><em>Monetary</em></strong>: The <strong><em>‘Loyal’ </em></strong>and <strong><em>‘Star’ </em></strong>segments show maximum values close to each other, as well as <strong><em>‘Potential loyal’ </em></strong>and <strong><em>‘Hold and improve,’</em></strong> but their minimum values are quite distant from each other (as verified by the mean).</li></ul><p>In the Segmentation by applying the K-means algorithm, the <strong>StandardScaler</strong> method was initially applied to standardize the values of <strong><em>‘Recency,’ ‘Frequency,’ </em></strong>and <strong><em>‘Monetary’</em></strong> due to the differences in their orders of magnitude. When choosing the number of clusters, the Elbow method was used, and due to the behavior and slope of the curve, the value 4 was adopted.</p><p>From the above, some suggestions can be adopted by <strong>Marketing:</strong></p><ul><li>Users in <strong>Cluster 0</strong> (a segment that combines the equivalent of <strong><em>‘Potential loyal’ </em></strong>and <strong><em>‘Hold and improve’</em></strong>) exhibit median behavior, with an average frequency of 45 purchases per day and 2624 users. Since this segment already shows low recency, an interesting approach would be to involve them in short-term promotions to increase purchase frequency.</li><li>For users in <strong>Cluster 1</strong> (equivalent to <strong><em>‘Risky’</em></strong> in RFM), who require more attention due to their quantity, involving them with voucher promotions or promotional products via emails and messages would be interesting. This could increase purchase frequency and engagement.</li><li>Users in <strong>Cluster 2</strong> (equivalent to the <strong><em>‘Star’</em></strong> group in RFM) are the most important users in the customer portfolio. As they are already loyal to the brand, the idea is not to overwhelm them with promotional emails and messages, saving time and resources for investment in other groups. One possibility could be considering something like a Loyalty Card.</li><li>Users in <strong>Cluster 3</strong> (equivalent to <strong><em>‘Loyal’</em></strong> in RFM) are those users who show good metrics of recency and frequency, meaning they buy regularly and in short periods but with low Monetary Value, indicating their purchases are likely low in value. Here, the approach would be to involve them in Loyalty Programs with selected higher-value products.</li></ul><p>If you have any doubts or suggestions, please don’t hesitate to contact me! Thank you very much for reading!</p><p>Connections:</p><ul><li><a href="https://github.com/alanpazribeiro"><strong><em>Github</em></strong></a></li><li><a href="https://www.linkedin.com/in/alan-paz-ribeiro-945a84259/"><strong><em>Linkedin</em></strong></a></li></ul><h3>5 — Bibliographical References</h3><ol><li>FORBES — Customer Segmentation: The Ultimate Guide — <a href="https://www.forbes.com/advisor/business/customer-segmentation/">https://www.forbes.com/advisor/business/customer-segmentation/</a>)</li><li>RFM analysis for Customer Segmentation — <a href="https://clevertap.com/blog/rfm-analysis/">https://clevertap.com/blog/rfm-analysis/</a></li><li>A quick guide to the RFM model for data scientists — <a href="https://practicaldatascience.co.uk/data-science/a-quick-guide-to-the-rfm-model">https://practicaldatascience.co.uk/data-science/a-quick-guide-to-the-rfm-model</a></li><li>RFM Analysis For Successful Customer Segmentation — <a href="https://www.putler.com/rfm-analysis/">https://www.putler.com/rfm-analysis/</a></li><li>Oztaysi, B. and Kavi, M., 2020, July. Fuzzy RFM Analysis: An Application in E-Commerce. In International Conference on Intelligent and Fuzzy Systems (pp. 1225–1232). Springer, Cham.</li><li>RFM ranking — An effective approach to customer segmentation — <a href="https://www.sciencedirect.com/science/article/pii/S1319157818304178">https://www.sciencedirect.com/science/article/pii/S1319157818304178</a></li><li>ResearchGate — Customer Segmentation in E- Commerce — <a href="https://www.researchgate.net/publication/355166048_Customer_Segmentation_in_E-_Commerce">https://www.researchgate.net/publication/355166048_Customer_Segmentation_in_E-_Commerce</a></li><li>Medium — Using RFM Analysis for Effective Customer Segmentation in Marketing — <a href="https://medium.com/@yennhi95zz/using-rfm-analysis-for-effective-customer-segmentation-in-marketing-4964a99bf606">https://medium.com/@yennhi95zz/using-rfm-analysis-for-effective-customer-segmentation-in-marketing-4964a99bf606</a></li><li>Medium — RFM with Python (Study Case: Ecommerce Dataset) — <a href="https://medium.com/@katarinanimas20/rfm-with-python-study-case-ecommerce-dataset-8327e09fce99">https://medium.com/@katarinanimas20/rfm-with-python-study-case-ecommerce-dataset-8327e09fce99</a></li><li>Medium — Data-Driven Customer Segmentation: RFM and CLTV Analysis Using Python — <a href="https://medium.com/@abdullahorzan/data-driven-customer-segmentation-rfm-and-cltv-analysis-using-python-4238b11bd740">https://medium.com/@abdullahorzan/data-driven-customer-segmentation-rfm-and-cltv-analysis-using-python-4238b11bd740</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ed31010dff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>