Unpivots
Unpivot unpivots a DataFrame from wide format to long format
Dataset
import nanuq
let df = newDataFrame:
A: ["a", "b", "a"]
B: [1, 3, 5]
C: [10, 11, 12]
D: [2, 4, 6]
nbShow df
shape: (3, 4)| A | B | C | D |
|---|
| str | i64 | i64 | i64 |
| "a" | 1 | 10 | 2 |
| "b" | 3 | 11 | 4 |
| "a" | 5 | 12 | 6 |
import polars as pl
df = pl.DataFrame(
{
"A": ["a", "b", "a"],
"B": [1, 3, 5],
"C": [10, 11, 12],
"D": [2, 4, 6],
}
)
df
shape: (3, 4)| A | B | C | D |
|---|
| str | i64 | i64 | i64 |
| "a" | 1 | 10 | 2 |
| "b" | 3 | 11 | 4 |
| "a" | 5 | 12 | 6 |
Eager + lazy
Eager and lazy have the same API.
let unpivoted = df.unpivot(["C", "D"], index = ["A", "B"])
nbShow unpivoted
shape: (6, 4)| A | B | variable | value |
|---|
| str | i64 | str | i64 |
| "a" | 1 | "C" | 10 |
| "b" | 3 | "C" | 11 |
| "a" | 5 | "C" | 12 |
| "a" | 1 | "D" | 2 |
| "b" | 3 | "D" | 4 |
| "a" | 5 | "D" | 6 |
df.unpivot(["C", "D"], index=["A", "B"])
shape: (6, 4)| A | B | variable | value |
|---|
| str | i64 | str | i64 |
| "a" | 1 | "C" | 10 |
| "b" | 3 | "C" | 11 |
| "a" | 5 | "C" | 12 |
| "a" | 1 | "D" | 2 |
| "b" | 3 | "D" | 4 |
| "a" | 5 | "D" | 6 |
import nanuqbook
bookInit()
nbText: "# Unpivots"
attribution userGuide("Unpivots", "transformations/unpivot", "")
nbText: """
Unpivot unpivots a DataFrame from wide format to long format
## Dataset
"""
tabs """
import polars as pl
df = pl.DataFrame(
{
"A": ["a", "b", "a"],
"B": [1, 3, 5],
"C": [10, 11, 12],
"D": [2, 4, 6],
}
)
df
""":
nbCode:
import nanuq
let df = newDataFrame:
A: ["a", "b", "a"]
B: [1, 3, 5]
C: [10, 11, 12]
D: [2, 4, 6]
nbShow df
nbText: """
## Eager + lazy
`Eager` and `lazy` have the same API.
"""
tabs """
df.unpivot(["C", "D"], index=["A", "B"])
""":
nbCode:
let unpivoted = df.unpivot(["C", "D"], index = ["A", "B"])
nbShow unpivoted
bookSave()
On GitHub: book/user-guide/unpivots.nim