Laboratório: Dados Relacionais com Polars

Author

Benilton S Carvalho

Objetivo

Os Dados

O banco de dados para esta atividade é o “IMDb Movie Data”, que possui informações sobre filmes, atores, diretores, gêneros e outros. Para os arquivos indicados abaixo, considere que o símbolo \N representa valores faltantes. Observe com cuidado a extensão dos arquivos para uma indicação do formato do mesmo.

1. title.basics.tsv.gz (Informações Básicas dos Filmes)

Coluna Descrição
tconst Identificador único do título (ex: tt1234567)
titleType Tipo do título (ex: movie, short, tvSeries)
primaryTitle Título principal
originalTitle Título original
isAdult Indica se é conteúdo adulto (0: não, 1: sim)
startYear Ano de lançamento/início
endYear Ano de término (para séries)
runtimeMinutes Duração em minutos
genres Gêneros separados por vírgula (ex: Action, Comedy)

2. title.ratings.tsv.gz (Avaliações dos Filmes)

Coluna Descrição
tconst Identificador único do título (ex: tt1234567)
averageRating Nota média dos usuários (escala de 1 a 10)
numVotes Número de votos recebidos

3. title.principals.tsv.gz (Elenco e Equipe Técnica)

Coluna Descrição
tconst Identificador único do título (ex: tt1234567)
nconst Identificador único da pessoa (ex: nm1234567)
category Categoria de trabalho da pessoa (ex: actor, director)
job Função específica desempenhada (para não-atores)
characters Personagens interpretados (para atores)

Atividade

Utilizando apenas operações por meio da biblioteca polars, responda:

  1. Quais são os 5 filmes com as maiores notas (averageRating)? Apresente uma solução capaz de desempatar os filmes baseando-se no número de votos recebidos.
  2. Qual é o gênero mais frequente entre os filmes com nota maior que 8?
  3. Quais são os 3 atores/atrizes que mais participaram de filmes com nota maior que 7.5?
import polars as pl

basics = pl.read_csv("C:/Users/benil/Downloads/title.basics0.tsv", separator = "\t", null_values = "\\N")
ratings = pl.read_csv("C:/Users/benil/Downloads/title.ratings.tsv.gz", separator = "\t", null_values = "\\N")
principals = pl.read_csv("C:/Users/benil/Downloads/title.principals.tsv.gz", separator = "\t", null_values = "\\N")
print(basics)
shape: (11_144_942, 9)
┌───────────┬───────────┬────────────┬───────────┬───┬───────────┬─────────┬───────────┬───────────┐
│ tconst    ┆ titleType ┆ primaryTit ┆ originalT ┆ … ┆ startYear ┆ endYear ┆ runtimeMi ┆ genres    │
│ ---       ┆ ---       ┆ le         ┆ itle      ┆   ┆ ---       ┆ ---     ┆ nutes     ┆ ---       │
│ str       ┆ str       ┆ ---        ┆ ---       ┆   ┆ i64       ┆ str     ┆ ---       ┆ str       │
│           ┆           ┆ str        ┆ str       ┆   ┆           ┆         ┆ i64       ┆           │
╞═══════════╪═══════════╪════════════╪═══════════╪═══╪═══════════╪═════════╪═══════════╪═══════════╡
│ tt0000001 ┆ short     ┆ Carmencita ┆ Carmencit ┆ … ┆ 1894      ┆ null    ┆ 1         ┆ Documenta │
│           ┆           ┆            ┆ a         ┆   ┆           ┆         ┆           ┆ ry,Short  │
│ tt0000002 ┆ short     ┆ Le clown   ┆ Le clown  ┆ … ┆ 1892      ┆ null    ┆ 5         ┆ Animation │
│           ┆           ┆ et ses     ┆ et ses    ┆   ┆           ┆         ┆           ┆ ,Short    │
│           ┆           ┆ chiens     ┆ chiens    ┆   ┆           ┆         ┆           ┆           │
│ tt0000003 ┆ short     ┆ Pauvre     ┆ Pauvre    ┆ … ┆ 1892      ┆ null    ┆ 5         ┆ Animation │
│           ┆           ┆ Pierrot    ┆ Pierrot   ┆   ┆           ┆         ┆           ┆ ,Comedy,R │
│           ┆           ┆            ┆           ┆   ┆           ┆         ┆           ┆ omance    │
│ tt0000004 ┆ short     ┆ Un bon     ┆ Un bon    ┆ … ┆ 1892      ┆ null    ┆ 12        ┆ Animation │
│           ┆           ┆ bock       ┆ bock      ┆   ┆           ┆         ┆           ┆ ,Short    │
│ tt0000005 ┆ short     ┆ Blacksmith ┆ Blacksmit ┆ … ┆ 1893      ┆ null    ┆ 1         ┆ Comedy,Sh │
│           ┆           ┆ Scene      ┆ h Scene   ┆   ┆           ┆         ┆           ┆ ort       │
│ …         ┆ …         ┆ …          ┆ …         ┆ … ┆ …         ┆ …       ┆ …         ┆ …         │
│ tt9916848 ┆ tvEpisode ┆ Episode    ┆ Episode   ┆ … ┆ 2009      ┆ null    ┆ null      ┆ Action,Dr │
│           ┆           ┆ 3.17       ┆ 3.17      ┆   ┆           ┆         ┆           ┆ ama,Famil │
│           ┆           ┆            ┆           ┆   ┆           ┆         ┆           ┆ y         │
│ tt9916850 ┆ tvEpisode ┆ Episode    ┆ Episode   ┆ … ┆ 2010      ┆ null    ┆ null      ┆ Action,Dr │
│           ┆           ┆ 3.19       ┆ 3.19      ┆   ┆           ┆         ┆           ┆ ama,Famil │
│           ┆           ┆            ┆           ┆   ┆           ┆         ┆           ┆ y         │
│ tt9916852 ┆ tvEpisode ┆ Episode    ┆ Episode   ┆ … ┆ 2010      ┆ null    ┆ null      ┆ Action,Dr │
│           ┆           ┆ 3.20       ┆ 3.20      ┆   ┆           ┆         ┆           ┆ ama,Famil │
│           ┆           ┆            ┆           ┆   ┆           ┆         ┆           ┆ y         │
│ tt9916856 ┆ short     ┆ The Wind   ┆ The Wind  ┆ … ┆ 2015      ┆ null    ┆ 27        ┆ Short     │
│ tt9916880 ┆ tvEpisode ┆ Horrid     ┆ Horrid    ┆ … ┆ 2014      ┆ null    ┆ 10        ┆ Adventure │
│           ┆           ┆ Henry      ┆ Henry     ┆   ┆           ┆         ┆           ┆ ,Animatio │
│           ┆           ┆ Knows It   ┆ Knows It  ┆   ┆           ┆         ┆           ┆ n,Comedy  │
│           ┆           ┆ All        ┆ All       ┆   ┆           ┆         ┆           ┆           │
└───────────┴───────────┴────────────┴───────────┴───┴───────────┴─────────┴───────────┴───────────┘
print(ratings)
shape: (1_484_615, 3)
┌───────────┬───────────────┬──────────┐
│ tconst    ┆ averageRating ┆ numVotes │
│ ---       ┆ ---           ┆ ---      │
│ str       ┆ f64           ┆ i64      │
╞═══════════╪═══════════════╪══════════╡
│ tt0000001 ┆ 5.7           ┆ 2092     │
│ tt0000002 ┆ 5.6           ┆ 283      │
│ tt0000003 ┆ 6.5           ┆ 2099     │
│ tt0000004 ┆ 5.4           ┆ 183      │
│ tt0000005 ┆ 6.2           ┆ 2835     │
│ …         ┆ …             ┆ …        │
│ tt9916730 ┆ 7.0           ┆ 12       │
│ tt9916766 ┆ 7.1           ┆ 24       │
│ tt9916778 ┆ 7.2           ┆ 37       │
│ tt9916840 ┆ 7.2           ┆ 10       │
│ tt9916880 ┆ 8.6           ┆ 8        │
└───────────┴───────────────┴──────────┘
print(principals)
shape: (86_420_004, 6)
┌───────────┬──────────┬───────────┬─────────────────┬─────────────────────────┬────────────┐
│ tconst    ┆ ordering ┆ nconst    ┆ category        ┆ job                     ┆ characters │
│ ---       ┆ ---      ┆ ---       ┆ ---             ┆ ---                     ┆ ---        │
│ str       ┆ i64      ┆ str       ┆ str             ┆ str                     ┆ str        │
╞═══════════╪══════════╪═══════════╪═════════════════╪═════════════════════════╪════════════╡
│ tt0000001 ┆ 1        ┆ nm1588970 ┆ self            ┆ null                    ┆ ["Self"]   │
│ tt0000001 ┆ 2        ┆ nm0005690 ┆ director        ┆ null                    ┆ null       │
│ tt0000001 ┆ 3        ┆ nm0005690 ┆ producer        ┆ producer                ┆ null       │
│ tt0000001 ┆ 4        ┆ nm0374658 ┆ cinematographer ┆ director of photography ┆ null       │
│ tt0000002 ┆ 1        ┆ nm0721526 ┆ director        ┆ null                    ┆ null       │
│ …         ┆ …        ┆ …         ┆ …               ┆ …                       ┆ …          │
│ tt9916880 ┆ 17       ┆ nm0996406 ┆ director        ┆ principal director      ┆ null       │
│ tt9916880 ┆ 18       ┆ nm1482639 ┆ writer          ┆ null                    ┆ null       │
│ tt9916880 ┆ 19       ┆ nm2586970 ┆ writer          ┆ books                   ┆ null       │
│ tt9916880 ┆ 20       ┆ nm1594058 ┆ producer        ┆ producer                ┆ null       │
│ tt9916880 ┆ 21       ┆ nm1482639 ┆ producer        ┆ producer                ┆ null       │
└───────────┴──────────┴───────────┴─────────────────┴─────────────────────────┴────────────┘
## Q1: top5 com as maiores notas
top5 = (
  ratings.join(basics, on = "tconst")
  .sort(["averageRating", "numVotes"], descending = True)
  .select(["primaryTitle", "numVotes", "averageRating"])
  .head(5)
)
print(top5)
shape: (5, 3)
┌─────────────────────────────────┬──────────┬───────────────┐
│ primaryTitle                    ┆ numVotes ┆ averageRating │
│ ---                             ┆ ---      ┆ ---           │
│ str                             ┆ i64      ┆ f64           │
╞═════════════════════════════════╪══════════╪═══════════════╡
│ Ozymandias                      ┆ 228900   ┆ 10.0          │
│ Kadifeyi Kesfet                 ┆ 2904     ┆ 10.0          │
│ Tatilde CUK Oturur Mukemmel Du… ┆ 2878     ┆ 10.0          │
│ Inci Koleksiyonunu Kesfet!      ┆ 2812     ┆ 10.0          │
│ DeFacto Kis Festivali           ┆ 2676     ┆ 10.0          │
└─────────────────────────────────┴──────────┴───────────────┘
## Q2: genero mais frequente entre filmes com nota > 8
genres5 = (
  ratings.filter(pl.col("averageRating") > 8)
  .join(basics, on = "tconst", how = "inner")
  .select(["primaryTitle", "genres", "averageRating"])
  .group_by("genres").agg(pl.col("genres").len().alias("n"))
  .sort("n", descending = True).head(5)
)
print(genres5)
shape: (5, 2)
┌────────────────────────────┬───────┐
│ genres                     ┆ n     │
│ ---                        ┆ ---   │
│ str                        ┆ u32   │
╞════════════════════════════╪═══════╡
│ Comedy                     ┆ 23071 │
│ Documentary                ┆ 20835 │
│ Drama                      ┆ 20677 │
│ Action,Adventure,Animation ┆ 13149 │
│ Drama,Romance              ┆ 7394  │
└────────────────────────────┴───────┘
## Q3 top3 atores que mais particip de filmes com notas > 7.5
actors3 = (
  ratings.filter(pl.col("averageRating") > 7.5)
  .join(principals.filter(pl.col("category").is_in(["actor", "actress"])),
        on = "tconst", how = "inner")
  .group_by("nconst").agg(pl.count("nconst").alias("n"))
  .sort("n", descending = True).head(3)
)
print(actors3)
shape: (3, 2)
┌───────────┬──────┐
│ nconst    ┆ n    │
│ ---       ┆ ---  │
│ str       ┆ u32  │
╞═══════════╪══════╡
│ nm0048389 ┆ 3739 │
│ nm0217221 ┆ 2760 │
│ nm0444786 ┆ 2420 │
└───────────┴──────┘