Pivot longer-ing in Polars

Polars
Author

ChuckPR

Published

September 26, 2024

The Polars equivalent for pivot_longer from dplyR is melt.

dplyrR example (R)

suppressPackageStartupMessages(
  library('tidyverse')
)

otter_data = read_csv(
  'https://raw.githubusercontent.com/jcoliver/learn-r/gh-pages/data/otter-mandible-data.csv',
  col_types = cols()
)

otter_data |>
  pivot_longer(cols = matches('m\\d')) |>
  head() |>
  gt::gt()
species museum accession name value
A. cinerea AMNH 101458 m1 15.100
A. cinerea AMNH 101458 m2 27.790
A. cinerea AMNH 101458 m3 21.885
A. cinerea AMNH 101458 m4 13.010
A. cinerea AMNH 101458 m5 10.500
A. cinerea AMNH 101458 m6 61.635

Polars example (Python)

import polars as pl
from great_tables import GT

(
  pl.read_csv(
    'https://raw.githubusercontent.com/jcoliver/learn-r/gh-pages/data/otter-mandible-data.csv',
    null_values='NA'
  )
  .melt(id_vars=['species', 'museum', 'accession'])
  .head()
  .pipe(lambda df_: GT(df_))
)
species museum accession variable value
A. cinerea AMNH 101458 m1 15.1
A. cinerea AMNH 101461 m1 12.74
A. cinerea AMNH 101466 m1 12.425
A. cinerea AMNH 101635 m1 13.4
A. cinerea AMNH 101459 m1 14.4