Translate

martes, 13 de agosto de 2024

Python Polars mejorando el performance de pandas

Durante el último año cada vez más analista que trabajan con Big Data usan Polars frente a Panda para el análisis de datos.

Entre ambas librerías existe una gran diferencia que hace que sea posible que Polars tenga un performance mejor, frente a Pandas, la librería por excelencia.


Cómo está creado Polards frente a Pandas

Polars está escrita en un lenguaje a bajo nivel llamado Rust y además hace uso de forma más fácil del paralelismo en python. Esto provoca que consuma menos recursos.

Cómo usar esta libreria

Igual que usamos pd para importar la librería de pandas, para usar polars puedes usar lo siguiente:

import polars as pl

Para seleccionar columnas puedes usar select de la siguiente forma:

df.select(pl.all())

Y si quieres filtrar filas:
 
df.filter(pl.col("ref") == "c")


Si comparamos con pandas en cuanto a sintaxis puedes verla aquí que se similar pero necesitamos una chuleta ya que cambia. En comparación con pandas en más cercana al lenguaje natual, lo cual es de agradecer.

Eliminar filas con valores nulos:Pandas:
df.dropna()
Polars:
df.drop_nulls()


Visto todo esto para datasets grandes vale la pena medir el performance por si es tan grande la diferencia entre ambas librerias.


Más información


Y una comparación con pandas en cuanto a sintaxis :

domingo, 11 de agosto de 2024

Curva de Beneficio

Hace una semana compartieron en Linkedin un data product de Mike Rhodes ha super útil para poder visualizar el efecto que tiene en el coste los gastos en campañas de Marketing.

La Curva de Beneficio muestra cómo es probable que cambie el beneficio total a medida que cambia la inversión en marketing.

Para poder usar este gráfico necesitamos el gasto y las conversiones. a partir de este podremos ir calculando las demás métricas.

Algunos conceptos que debemos entender antes de empezar a meter datos y sacar conclusiones:

  • El Beneficio Incremental ;muestra el beneficio adicional obtenido por cada aumento en el gasto. Las barras positivas (verdes) indican aumentos de gasto rentables.
  • Beneficio Total frente al Retorno de la Inversión Publicitaria (ROAS), layuda a identificar el rango de ROAS que maximiza el beneficio.
  • El ROAS Marginal : muestra el retorno esperado de la inversión publicitaria correspondiente a un nivel de gasto, lo que ayuda a identificar los rendimientos decrecientes
El ROAS Marginal es un concepto bastante potente que suele pasar desapercibido para los equipos de Marketing pero que puede ser muy útil

Break even 



Profit max



Puedes acceder al data product en

martes, 2 de julio de 2024

K-means cluster - How to choose K

 One key step in K-means clustering is deciding on the number of clusters. Ideally, the data itself should guide us on the optimal number of groups.

There are several ways to detemine the number of cluster

This is what we want to achieve in a picture with our groups:


Elbow criterion

The elbow criterion helps us achieve this. It plots the ratio of within-cluster variance to between-cluster variance against the number of clusters. We want this ratio to be low, indicating tight clusters and high separation between them.

In a graph: 

It looks like this:


As we increase the number of clusters, this ratio initially drops significantly. However, there comes a point where adding more clusters doesn't lead to a substantial improvement. 

This point, known as the "elbow," is considered the ideal number of clusters.

More information about the elbow criterion

https://en.wikipedia.org/wiki/Elbow_method_(clustering)

domingo, 23 de junio de 2024

Customer segmentation with K-Means

 Today, let's unravel the magic of K-Means clustering, your trusty tool for discovering those hidden gems within your marketing data.

What's K-Means Clustering, you ask?

Think of K-Means as a way to group similar data points together, helping you uncover those underlying patterns that might not be obvious at first glance. It's like sorting your favorite candies into different piles based on their flavors – except in this case, we're using customer data like demographics or location.

How Does It Work?

  1. Choose K: First, you need to decide how many clusters (K) you want. It's like deciding how many candy piles you'll have! We'll talk about how to find the perfect K later.
  2. Random Centers: Imagine randomly picking K candies as the starting centers for your piles. That's what we do with your data – randomly select K points as the initial cluster centers (centroids).
  3. Calculate Distances: Now, measure the distance between each data point (candy) and each center (pile). We use the Euclidean distance formula (don't worry, it's not as scary as it sounds!).
  4. Group Them Up: Assign each data point to the closest center, creating your clusters!
  5. Find New Centers: Re-calculate the center of each new cluster (like finding the average position of all the candies in a pile).
  6. Repeat: Keep repeating steps 3-5 until your clusters stop changing much. You've found your final clusters!

Validate Your Clusters:

  • Check the Variance: How tightly packed are the data points within each cluster? Low variance is good, like having candies that are all very similar in flavor within each pile.
  • Dunn Index: This fancy index measures both the tightness of your clusters and how far apart they are. Aim for a high Dunn Index – it means your clusters are well-defined and distinct.

Remember:

  • K-Means is just a tool, not magic! You'll need to use your marketing expertise to interpret the clusters and give them meaningful names.
  • I´ll cover how to find the best K and name your segments in upcoming posts.