library(reticulate)#abrindo o pacote reticulate
Desafio 10
##Introducao ao polars
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
= pl.read_csv("airports.csv",
aeroportos = ["IATA_CODE", "CITY", "STATE"])
columns 2) aeroportos.head(
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
= pl.read_excel("WDIEXCEL.xlsx", sheet_name = "Country",
wdi = ["Short Name", "Region"])
columns 2) wdi.head(
shape: (2, 2)
Short Name | Region |
---|---|
str | str |
"Aruba" | "Latin America & Caribbean" |
"Africa Eastern and Southern" | null |
= pl.DataFrame({
df "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 |
"valor1"] df[
shape: (5,)
valor1 |
---|
i64 |
10 |
15 |
10 |
null |
25 |
"valor1"].drop_nulls() df[
shape: (4,)
valor1 |
---|
i64 |
10 |
15 |
10 |
25 |
"valor1"].drop_nulls().mean() df[
15.0
df.select(["valor1").mean().alias("media_v1"),
pl.col("valor2").mean()
pl.col( ])
shape: (1, 2)
media_v1 | valor2 |
---|---|
f64 | f64 |
15.0 | 18.333333 |
"grupo").agg([
df.group_by("valor1").mean().alias("media_valor1"),
pl.col("valor2").min().alias("min_valor2")
pl.col("grupo") ]).sort(
shape: (3, 3)
grupo | media_valor1 | min_valor2 |
---|---|---|
str | f64 | i64 |
"A" | 12.5 | 5 |
"B" | 10.0 | 20 |
"C" | 25.0 | null |
= pl.read_csv("flights.csv",
voos = ["AIRLINE", "ARRIVAL_DELAY", "DESTINATION_AIRPORT"],
columns = {"AIRLINE": pl.Utf8,
schema_overrides "ARRIVAL_DELAY": pl.Int32,
"DESTINATION_AIRPORT": pl.Utf8})
voos.shape
(5819079, 3)
3) voos.head(
shape: (3, 3)
AIRLINE | DESTINATION_AIRPORT | ARRIVAL_DELAY |
---|---|---|
str | str | i32 |
"AS" | "SEA" | -22 |
"AA" | "PBI" | -9 |
"US" | "CLT" | 5 |
= (
resultado "AIRLINE", "DESTINATION_AIRPORT", "ARRIVAL_DELAY"])
voos.drop_nulls([filter(
."AIRLINE").is_in(["AA", "DL"]) &
pl.col("DESTINATION_AIRPORT").is_in(["SEA", "MIA", "BWI"])
pl.col(
)"AIRLINE", "DESTINATION_AIRPORT"])
.group_by([
.agg(["ARRIVAL_DELAY") > 30).mean().alias("atraso_medio")
(pl.col(
]) )
"atraso_medio") resultado.sort(
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
= pl.DataFrame({
clientes "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 │
└────────────┴────────┘
= pl.DataFrame({
pedidos "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 │
└───────────┴────────────┴────────┘
= clientes.join(pedidos, on="cliente_id", how="inner")
res_ij 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 │
└────────────┴───────┴───────────┴────────┘
= clientes.join(pedidos, on="cliente_id", how="left")
res_lj 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 │
└────────────┴────────┴───────────┴────────┘
= clientes.join(pedidos, on="cliente_id", how="right")
res_rj 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
= clientes.join(pedidos, on="cliente_id", how="full")
res_oj 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")
= clientes.join(pedidos, how="cross")
res_cj 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_ij.group_by(["nome", "cliente_id"]).agg(pl.col("valor").mean())
res 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_oj.with_columns(pl.col("valor") > 100)
res "nome")
.group_by("valor").sum()))
.agg(pl.col(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
= pl.DataFrame({
vendas "id_venda": [1, 2, 3],
"id_cl": [1, 2, 1],
"id_prod": [101, 102, 103],
"qtde": [2, 1, 1]
})
= pl.DataFrame({
detalhes_pedidos "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 │
└────────┴───────┴─────────┴───────┘
= vendas.join(detalhes_pedidos,
final = ["id_cl", "id_prod"],
left_on = ["cl_id", "id_prod"],
right_on = "inner")
how 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
<- Sys.time()
horario_geracao
# 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>