Desafio 10

##Introducao ao polars

library(reticulate)#abrindo o pacote reticulate
virtualenv_create("env_me315", python = "C:/Program Files/Python312/python.exe")#criando um ambiente virtual pra usar python
virtualenv: env_me315
use_virtualenv("env_me315", required = TRUE) #manda usar o ambiente virtual criado
#!pip install polars
#!pip install fastexcel
import polars as pl
## Lembre-se que já carregamos a biblioteca
import polars as pl
aeroportos = pl.read_csv("airports.csv",
                         columns = ["IATA_CODE", "CITY", "STATE"])
aeroportos.head(2)
shape: (2, 3)
IATA_CODE CITY STATE
str str str
"ABE" "Allentown" "PA"
"ABI" "Abilene" "TX"
#!pip install pyarrow #dependencia para executar o proximo codigo
#corringindo
wdi = pl.read_excel("WDIEXCEL.xlsx", sheet_name = "Country",
                    columns = ["Short Name", "Region"])
wdi.head(2)
shape: (2, 2)
Short Name Region
str str
"Aruba" "Latin America & Caribbean"
"Africa Eastern and Southern" null
df = pl.DataFrame({
    "grupo": ["A", "A", "B", "B", "C"],
    "valor1": [10, 15, 10, None, 25],
    "valor2": [5, None, 20, 30, None]
})
df
shape: (5, 3)
grupo valor1 valor2
str i64 i64
"A" 10 5
"A" 15 null
"B" 10 20
"B" null 30
"C" 25 null
df["valor1"]
shape: (5,)
valor1
i64
10
15
10
null
25
df["valor1"].drop_nulls()
shape: (4,)
valor1
i64
10
15
10
25
df["valor1"].drop_nulls().mean()
15.0
df.select([
  pl.col("valor1").mean().alias("media_v1"),
  pl.col("valor2").mean()
])
shape: (1, 2)
media_v1 valor2
f64 f64
15.0 18.333333
df.group_by("grupo").agg([
  pl.col("valor1").mean().alias("media_valor1"),
  pl.col("valor2").min().alias("min_valor2")
]).sort("grupo")
shape: (3, 3)
grupo media_valor1 min_valor2
str f64 i64
"A" 12.5 5
"B" 10.0 20
"C" 25.0 null
voos = pl.read_csv("flights.csv",
                   columns = ["AIRLINE", "ARRIVAL_DELAY", "DESTINATION_AIRPORT"],
                   schema_overrides = {"AIRLINE": pl.Utf8,
                             "ARRIVAL_DELAY": pl.Int32,
                             "DESTINATION_AIRPORT": pl.Utf8})
voos.shape
(5819079, 3)
voos.head(3)
shape: (3, 3)
AIRLINE DESTINATION_AIRPORT ARRIVAL_DELAY
str str i32
"AS" "SEA" -22
"AA" "PBI" -9
"US" "CLT" 5
resultado = (
  voos.drop_nulls(["AIRLINE", "DESTINATION_AIRPORT", "ARRIVAL_DELAY"])
  .filter(
    pl.col("AIRLINE").is_in(["AA", "DL"]) &
    pl.col("DESTINATION_AIRPORT").is_in(["SEA", "MIA", "BWI"])
    )
    .group_by(["AIRLINE", "DESTINATION_AIRPORT"])
    .agg([
      (pl.col("ARRIVAL_DELAY") > 30).mean().alias("atraso_medio")
      ])
)
resultado.sort("atraso_medio")
shape: (6, 3)
AIRLINE DESTINATION_AIRPORT atraso_medio
str str f64
"DL" "BWI" 0.069455
"DL" "SEA" 0.072967
"DL" "MIA" 0.090467
"AA" "MIA" 0.117894
"AA" "SEA" 0.124212
"AA" "BWI" 0.127523

Dados relacionais com Polars

import polars as pl

# Criando DataFrames
clientes = pl.DataFrame({
    "cliente_id": [1, 2, 3, 4],
    "nome": ["Ana", "Bruno", "Clara", "Daniel"]
})

print(clientes)
shape: (4, 2)
┌────────────┬────────┐
│ cliente_id ┆ nome   │
│ ---        ┆ ---    │
│ i64        ┆ str    │
╞════════════╪════════╡
│ 1          ┆ Ana    │
│ 2          ┆ Bruno  │
│ 3          ┆ Clara  │
│ 4          ┆ Daniel │
└────────────┴────────┘
pedidos = pl.DataFrame({
    "pedido_id": [101, 102, 103, 104, 105],
    "cliente_id": [1, 2, 3, 1, 5],
    "valor": [100.50, 250.75, 75.00, 130.00, 79.00]
})

print(pedidos)
shape: (5, 3)
┌───────────┬────────────┬────────┐
│ pedido_id ┆ cliente_id ┆ valor  │
│ ---       ┆ ---        ┆ ---    │
│ i64       ┆ i64        ┆ f64    │
╞═══════════╪════════════╪════════╡
│ 101       ┆ 1          ┆ 100.5  │
│ 102       ┆ 2          ┆ 250.75 │
│ 103       ┆ 3          ┆ 75.0   │
│ 104       ┆ 1          ┆ 130.0  │
│ 105       ┆ 5          ┆ 79.0   │
└───────────┴────────────┴────────┘
res_ij = clientes.join(pedidos, on="cliente_id", how="inner")
print(res_ij)
shape: (4, 4)
┌────────────┬───────┬───────────┬────────┐
│ cliente_id ┆ nome  ┆ pedido_id ┆ valor  │
│ ---        ┆ ---   ┆ ---       ┆ ---    │
│ i64        ┆ str   ┆ i64       ┆ f64    │
╞════════════╪═══════╪═══════════╪════════╡
│ 1          ┆ Ana   ┆ 101       ┆ 100.5  │
│ 2          ┆ Bruno ┆ 102       ┆ 250.75 │
│ 3          ┆ Clara ┆ 103       ┆ 75.0   │
│ 1          ┆ Ana   ┆ 104       ┆ 130.0  │
└────────────┴───────┴───────────┴────────┘
res_lj = clientes.join(pedidos, on="cliente_id", how="left")
print(res_lj)
shape: (5, 4)
┌────────────┬────────┬───────────┬────────┐
│ cliente_id ┆ nome   ┆ pedido_id ┆ valor  │
│ ---        ┆ ---    ┆ ---       ┆ ---    │
│ i64        ┆ str    ┆ i64       ┆ f64    │
╞════════════╪════════╪═══════════╪════════╡
│ 1          ┆ Ana    ┆ 101       ┆ 100.5  │
│ 1          ┆ Ana    ┆ 104       ┆ 130.0  │
│ 2          ┆ Bruno  ┆ 102       ┆ 250.75 │
│ 3          ┆ Clara  ┆ 103       ┆ 75.0   │
│ 4          ┆ Daniel ┆ null      ┆ null   │
└────────────┴────────┴───────────┴────────┘
res_rj = clientes.join(pedidos, on="cliente_id", how="right")
print(res_rj)
shape: (5, 4)
┌───────┬───────────┬────────────┬────────┐
│ nome  ┆ pedido_id ┆ cliente_id ┆ valor  │
│ ---   ┆ ---       ┆ ---        ┆ ---    │
│ str   ┆ i64       ┆ i64        ┆ f64    │
╞═══════╪═══════════╪════════════╪════════╡
│ Ana   ┆ 101       ┆ 1          ┆ 100.5  │
│ Bruno ┆ 102       ┆ 2          ┆ 250.75 │
│ Clara ┆ 103       ┆ 3          ┆ 75.0   │
│ Ana   ┆ 104       ┆ 1          ┆ 130.0  │
│ null  ┆ 105       ┆ 5          ┆ 79.0   │
└───────┴───────────┴────────────┴────────┘
#corrigindo a versao antiga
res_oj = clientes.join(pedidos, on="cliente_id", how="full")
print(res_oj)
shape: (6, 5)
┌────────────┬────────┬───────────┬──────────────────┬────────┐
│ cliente_id ┆ nome   ┆ pedido_id ┆ cliente_id_right ┆ valor  │
│ ---        ┆ ---    ┆ ---       ┆ ---              ┆ ---    │
│ i64        ┆ str    ┆ i64       ┆ i64              ┆ f64    │
╞════════════╪════════╪═══════════╪══════════════════╪════════╡
│ 1          ┆ Ana    ┆ 101       ┆ 1                ┆ 100.5  │
│ 2          ┆ Bruno  ┆ 102       ┆ 2                ┆ 250.75 │
│ 3          ┆ Clara  ┆ 103       ┆ 3                ┆ 75.0   │
│ 1          ┆ Ana    ┆ 104       ┆ 1                ┆ 130.0  │
│ null       ┆ null   ┆ 105       ┆ 5                ┆ 79.0   │
│ 4          ┆ Daniel ┆ null      ┆ null             ┆ null   │
└────────────┴────────┴───────────┴──────────────────┴────────┘
#corrigindo (retirando o "on="cliente_id")
res_cj = clientes.join(pedidos, how="cross")
print(res_cj)
shape: (20, 5)
┌────────────┬────────┬───────────┬──────────────────┬────────┐
│ cliente_id ┆ nome   ┆ pedido_id ┆ cliente_id_right ┆ valor  │
│ ---        ┆ ---    ┆ ---       ┆ ---              ┆ ---    │
│ i64        ┆ str    ┆ i64       ┆ i64              ┆ f64    │
╞════════════╪════════╪═══════════╪══════════════════╪════════╡
│ 1          ┆ Ana    ┆ 101       ┆ 1                ┆ 100.5  │
│ 1          ┆ Ana    ┆ 102       ┆ 2                ┆ 250.75 │
│ 1          ┆ Ana    ┆ 103       ┆ 3                ┆ 75.0   │
│ 1          ┆ Ana    ┆ 104       ┆ 1                ┆ 130.0  │
│ 1          ┆ Ana    ┆ 105       ┆ 5                ┆ 79.0   │
│ …          ┆ …      ┆ …         ┆ …                ┆ …      │
│ 4          ┆ Daniel ┆ 101       ┆ 1                ┆ 100.5  │
│ 4          ┆ Daniel ┆ 102       ┆ 2                ┆ 250.75 │
│ 4          ┆ Daniel ┆ 103       ┆ 3                ┆ 75.0   │
│ 4          ┆ Daniel ┆ 104       ┆ 1                ┆ 130.0  │
│ 4          ┆ Daniel ┆ 105       ┆ 5                ┆ 79.0   │
└────────────┴────────┴───────────┴──────────────────┴────────┘

#P1 Qual o valor medio das compras realizadas para cada cliente indentificado

print(clientes)
shape: (4, 2)
┌────────────┬────────┐
│ cliente_id ┆ nome   │
│ ---        ┆ ---    │
│ i64        ┆ str    │
╞════════════╪════════╡
│ 1          ┆ Ana    │
│ 2          ┆ Bruno  │
│ 3          ┆ Clara  │
│ 4          ┆ Daniel │
└────────────┴────────┘
print(pedidos)
shape: (5, 3)
┌───────────┬────────────┬────────┐
│ pedido_id ┆ cliente_id ┆ valor  │
│ ---       ┆ ---        ┆ ---    │
│ i64       ┆ i64        ┆ f64    │
╞═══════════╪════════════╪════════╡
│ 101       ┆ 1          ┆ 100.5  │
│ 102       ┆ 2          ┆ 250.75 │
│ 103       ┆ 3          ┆ 75.0   │
│ 104       ┆ 1          ┆ 130.0  │
│ 105       ┆ 5          ┆ 79.0   │
└───────────┴────────────┴────────┘
res = res_ij.group_by(["nome", "cliente_id"]).agg(pl.col("valor").mean())
print(res)
shape: (3, 3)
┌───────┬────────────┬────────┐
│ nome  ┆ cliente_id ┆ valor  │
│ ---   ┆ ---        ┆ ---    │
│ str   ┆ i64        ┆ f64    │
╞═══════╪════════════╪════════╡
│ Clara ┆ 3          ┆ 75.0   │
│ Ana   ┆ 1          ┆ 115.25 │
│ Bruno ┆ 2          ┆ 250.75 │
└───────┴────────────┴────────┘

#P2 Informe os nomes e a quantidade de compras com valor mínimo de $100.00 realizadas por cada cliente.

print(clientes)
shape: (4, 2)
┌────────────┬────────┐
│ cliente_id ┆ nome   │
│ ---        ┆ ---    │
│ i64        ┆ str    │
╞════════════╪════════╡
│ 1          ┆ Ana    │
│ 2          ┆ Bruno  │
│ 3          ┆ Clara  │
│ 4          ┆ Daniel │
└────────────┴────────┘
print(pedidos)
shape: (5, 3)
┌───────────┬────────────┬────────┐
│ pedido_id ┆ cliente_id ┆ valor  │
│ ---       ┆ ---        ┆ ---    │
│ i64       ┆ i64        ┆ f64    │
╞═══════════╪════════════╪════════╡
│ 101       ┆ 1          ┆ 100.5  │
│ 102       ┆ 2          ┆ 250.75 │
│ 103       ┆ 3          ┆ 75.0   │
│ 104       ┆ 1          ┆ 130.0  │
│ 105       ┆ 5          ┆ 79.0   │
└───────────┴────────────┴────────┘
res = (res_oj.with_columns(pl.col("valor") > 100)
       .group_by("nome")
       .agg(pl.col("valor").sum()))
print(res)
shape: (5, 2)
┌────────┬───────┐
│ nome   ┆ valor │
│ ---    ┆ ---   │
│ str    ┆ u32   │
╞════════╪═══════╡
│ Clara  ┆ 0     │
│ Bruno  ┆ 1     │
│ Daniel ┆ 0     │
│ Ana    ┆ 2     │
│ null   ┆ 0     │
└────────┴───────┘

#JOIN com Múltiplas Colunas como Chave

vendas = pl.DataFrame({
    "id_venda": [1, 2, 3],
    "id_cl": [1, 2, 1],
    "id_prod": [101, 102, 103],
    "qtde": [2, 1, 1]
})

detalhes_pedidos = pl.DataFrame({
    "id_ped": [201, 202, 203],
    "cl_id": [1, 2, 1],
    "id_prod": [101, 102, 104],
    "valor": [50.00, 75.00, 100.00]
})
print(vendas)
shape: (3, 4)
┌──────────┬───────┬─────────┬──────┐
│ id_venda ┆ id_cl ┆ id_prod ┆ qtde │
│ ---      ┆ ---   ┆ ---     ┆ ---  │
│ i64      ┆ i64   ┆ i64     ┆ i64  │
╞══════════╪═══════╪═════════╪══════╡
│ 1        ┆ 1     ┆ 101     ┆ 2    │
│ 2        ┆ 2     ┆ 102     ┆ 1    │
│ 3        ┆ 1     ┆ 103     ┆ 1    │
└──────────┴───────┴─────────┴──────┘
print(detalhes_pedidos)
shape: (3, 4)
┌────────┬───────┬─────────┬───────┐
│ id_ped ┆ cl_id ┆ id_prod ┆ valor │
│ ---    ┆ ---   ┆ ---     ┆ ---   │
│ i64    ┆ i64   ┆ i64     ┆ f64   │
╞════════╪═══════╪═════════╪═══════╡
│ 201    ┆ 1     ┆ 101     ┆ 50.0  │
│ 202    ┆ 2     ┆ 102     ┆ 75.0  │
│ 203    ┆ 1     ┆ 104     ┆ 100.0 │
└────────┴───────┴─────────┴───────┘
final = vendas.join(detalhes_pedidos,
                    left_on = ["id_cl", "id_prod"],
                    right_on = ["cl_id", "id_prod"],
                    how = "inner")
print(final)
shape: (2, 6)
┌──────────┬───────┬─────────┬──────┬────────┬───────┐
│ id_venda ┆ id_cl ┆ id_prod ┆ qtde ┆ id_ped ┆ valor │
│ ---      ┆ ---   ┆ ---     ┆ ---  ┆ ---    ┆ ---   │
│ i64      ┆ i64   ┆ i64     ┆ i64  ┆ i64    ┆ f64   │
╞══════════╪═══════╪═════════╪══════╪════════╪═══════╡
│ 1        ┆ 1     ┆ 101     ┆ 2    ┆ 201    ┆ 50.0  │
│ 2        ┆ 2     ┆ 102     ┆ 1    ┆ 202    ┆ 75.0  │
└──────────┴───────┴─────────┴──────┴────────┴───────┘
# Captura o horário atual
horario_geracao <- Sys.time()

# Mostrar no console
horario_geracao
[1] "2025-10-02 11:02:01 -03"
# Ou inserir em um HTML (exemplo com cat)
cat("<p>Relatório gerado em:", horario_geracao, "</p>")
<p>Relatório gerado em: 1759413722 </p>