Selecting and creating columns

Most of what you do to a frame comes down to two verbs: select, which keeps the columns you name (and computes new ones), and withColumns, which keeps all the columns and adds or replaces some. This chapter plays with both on a table of Star Wars characters, reduced to three rebels.

import nanuq

let starwars = readParquet("data/definitive-guide/starwars.parquet")
let rebels = starwars.drop("films").filter(
  col.name.isIn(["Luke Skywalker", "Leia Organa", "Han Solo"]))

nbShow rebels.select(col("name", "height", "mass", "hair_color", "skin_color", "eye_color"))
shape: (3, 6)
nameheightmasshair_colorskin_coloreye_color
stru16f64strstrstr
"Han Solo"18080.0"brown""fair""brown"
"Leia Organa"15049.0"brown""light""brown"
"Luke Skywalker"17277.0"blond""fair""blue"
nbShow rebels.select(col("birth_year", "sex", "gender", "homeworld", "species"))
shape: (3, 5)
birth_yearsexgenderhomeworldspecies
f64catcatstrstr
29.0"male""masculine""Corellia""Human"
19.0"female""feminine""Alderaan""Human"
19.0"male""masculine""Tatooine""Human"
nbShow rebels.select(col("vehicles", "starships", "birth_date", "screen_time"))
shape: (3, 4)
vehiclesstarshipsbirth_datescreen_time
list[str]list[str]dateduration[ΞΌs]
null["Millennium Falcon", "Imperial shuttle"]1948-06-011h 12m 37s
["Imperial Speeder Bike"]null1958-05-301h 3m 40s
["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-301h 58m 44s

Selecting Columns

select takes column names, col expressions, regular expressions on the names, and new columns computed from the old ones:

nbShow rebels.select(
  col.name,
  col.homeworld,
  col("^.*_color$"),
  (col.height / 100).alias("height_m"))
shape: (3, 6)
namehomeworldhair_colorskin_coloreye_colorheight_m
strstrstrstrstrf64
"Han Solo""Corellia""brown""fair""brown"1.8
"Leia Organa""Alderaan""brown""light""brown"1.5
"Luke Skywalker""Tatooine""blond""fair""blue"1.72

Introducing Selectors

Selectors pick columns by name, type or position, and can be combined like sets.

import polars.selectors as cs

rebels.select(
    "name",
    cs.by_name("homeworld"),
    cs.matches("^.*_color$"),
    (cs.by_name("height") / 100).alias("height_m"),
)
shape: (3, 6)
namehomeworldhair_colorskin_coloreye_colorheight_m
strstrstrstrstrf64
"Han Solo""Corellia""brown""fair""brown"1.8
"Leia Organa""Alderaan""brown""light""brown"1.5
"Luke Skywalker""Tatooine""blond""fair""blue"1.72

Selecting Based on Name

nbShow rebels.select(col("^birth_.*$"))
shape: (3, 2)
birth_yearbirth_date
f64date
29.01948-06-01
19.01958-05-30
19.01958-05-30
nbShow rebels.select(col("^.*_color$"))
shape: (3, 3)
hair_colorskin_coloreye_color
strstrstr
"brown""fair""brown"
"brown""light""brown"
"blond""fair""blue"
nbShow rebels.select(col("^.*_.*$"))
shape: (3, 6)
hair_colorskin_coloreye_colorbirth_yearbirth_datescreen_time
strstrstrf64dateduration[ΞΌs]
"brown""fair""brown"29.01948-06-011h 12m 37s
"brown""light""brown"19.01958-05-301h 3m 40s
"blond""fair""blue"19.01958-05-301h 58m 44s
nbShow rebels.select(col("^[a-z]{4}$"))
shape: (3, 2)
namemass
strf64
"Han Solo"80.0
"Leia Organa"49.0
"Luke Skywalker"77.0

Selecting Based on Data Type

nbShow rebels.groupBy(col.hair_color).agg(col(SomeNumber).mean)
shape: (2, 4)
hair_colorheightmassbirth_year
strf64f64f64
"brown"165.064.524.0
"blond"172.077.019.0
nbShow rebels.select(col(string))
shape: (3, 6)
namehair_colorskin_coloreye_colorhomeworldspecies
strstrstrstrstrstr
"Han Solo""brown""fair""brown""Corellia""Human"
"Leia Organa""brown""light""brown""Alderaan""Human"
"Luke Skywalker""blond""fair""blue""Tatooine""Human"
nbShow rebels.select(col(Date, Duration))
shape: (3, 2)
birth_datescreen_time
dateduration[ΞΌs]
1948-06-011h 12m 37s
1958-05-301h 3m 40s
1958-05-301h 58m 44s
nbShow rebels.select(col(seq[string]))
shape: (3, 2)
vehiclesstarships
list[str]list[str]
null["Millennium Falcon", "Imperial shuttle"]
["Imperial Speeder Bike"]null
["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]

Selecting Based on Position

Python only: Nanuq has no by_index.

rebels.select("name", cs.by_index(range(-2, 0)))
shape: (3, 3)
namebirth_datescreen_time
strdateduration[ΞΌs]
"Han Solo"1948-06-011h 12m 37s
"Leia Organa"1958-05-301h 3m 40s
"Luke Skywalker"1958-05-301h 58m 44s

Combining Selectors

Selectors combine with | (union), & (intersection), - (difference), ^ and ~ (complement):

rebels.select(cs.by_name("hair_color") | cs.numeric())
shape: (3, 4)
heightmasshair_colorbirth_year
u16f64strf64
18080.0"brown"29.0
15049.0"brown"19.0
17277.0"blond"19.0

Creating Columns

withColumns adds new columns, here the body mass index of each rebel:

nbShow rebels.withColumns((col.mass / pow(col.height / 100, 2)).alias("bmi"))
shape: (3, 16)
nameheightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_datescreen_timebmi
stru16f64strstrstrf64catcatstrstrlist[str]list[str]dateduration[ΞΌs]f64
"Han Solo"18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-011h 12m 37s24.691358
"Leia Organa"15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-301h 3m 40s21.777778
"Luke Skywalker"17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-301h 58m 44s26.027582

An expression on an existing column, without a new name, replaces it:

let df = newDataFrame:
  a: [1, 2, 3]
nbShow df.withColumns(col.a * 2)
shape: (3, 1)
a
i64
2
4
6
nbShow df.withColumns((col.a * 2).alias("a2"))
shape: (3, 2)
aa2
i64i64
12
24
36

Several columns at once. The second one is the rebels' age in whole years on the day Return of the Jedi came out:

nbShow rebels.withColumns(
  (col.mass / pow(col.height / 100, 2)).alias("bmi"),
  ((date(1983, 5, 25) - col.birth_date).dt.totalDays / 365).cast(uint8)
    .alias("age_destroy"))
shape: (3, 17)
nameheightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_datescreen_timebmiage_destroy
stru16f64strstrstrf64catcatstrstrlist[str]list[str]dateduration[ΞΌs]f64u8
"Han Solo"18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-011h 12m 37s24.69135835
"Leia Organa"15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-301h 3m 40s21.77777825
"Luke Skywalker"17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-301h 58m 44s26.02758225

The columns in one withColumns are computed side by side, so one cannot use another: the book shows that referring to bmi in the same call raises a ColumnNotFoundError, and that two calls in a row work. The second call bins the BMI with cut:

nbShow rebels.withColumns(
    (col.mass / pow(col.height / 100, 2)).alias("bmi")
  ).withColumns(
    col.bmi.cut([18.5, 25], labels = ["Underweight", "Normal", "Overweight"])
      .alias("bmi_cat"))
shape: (3, 17)
nameheightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_datescreen_timebmibmi_cat
stru16f64strstrstrf64catcatstrstrlist[str]list[str]dateduration[ΞΌs]f64enum
"Han Solo"18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-011h 12m 37s24.691358"Normal"
"Leia Organa"15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-301h 3m 40s21.777778"Normal"
"Luke Skywalker"17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-301h 58m 44s26.027582"Overweight"

select creates columns too. The five characters with the highest BMI:

nbShow starwars.select(
    col.name,
    (col.mass / pow(col.height / 100, 2)).alias("bmi"),
    col.species)
  .dropNulls()
  .topK(5, by = "bmi")
shape: (5, 3)
namebmispecies
strf64str
"Jabba Desilijic Tiure"443.428571"Hutt"
"Dud Bolt"50.928022"Vulptereen"
"Yoda"39.02663"Yoda's species"
"Owen Lars"37.874006"Human"
"IG-88"35.0"Droid"

A literal is broadcast to every row:

nbShow df.withColumns(lit(1).alias("ones"))
shape: (3, 2)
aones
i64i32
11
21
31
nbShow df.select(all(), lit(1).alias("ones"))
shape: (3, 2)
aones
i64i32
11
21
31

Related Column Operations

Dropping

With strict=False, names that are not in the frame (here screen_time is, but it need not be) are ignored:

nbShow rebels.drop(["name", "screen_time"], strict = false)
shape: (3, 13)
heightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_date
u16f64strstrstrf64catcatstrstrlist[str]list[str]date
18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-01
15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-30
17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-30
nbShow rebels.select(all().exclude("name", "screen_time"))
shape: (3, 13)
heightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_date
u16f64strstrstrf64catcatstrstrlist[str]list[str]date
18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-01
15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-30
17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-30
nbShow rebels.select(all().exclude("name", "screen_time"))
shape: (3, 13)
heightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_date
u16f64strstrstrf64catcatstrstrlist[str]list[str]date
18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-01
15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-30
17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-30

Renaming

nbShow rebels.rename({"homeworld": "planet", "mass": "weight"})
  .rename({"hair_color": "hair", "skin_color": "skin", "eye_color": "eye"})
  .select(col("name", "planet", "weight", "hair", "skin", "eye"))
shape: (3, 6)
nameplanetweighthairskineye
strstrf64strstrstr
"Han Solo""Corellia"80.0"brown""fair""brown"
"Leia Organa""Alderaan"49.0"brown""light""brown"
"Luke Skywalker""Tatooine"77.0"blond""fair""blue"

Stacking

let rebelNames = rebels.select(col.name)
let rebelColors = rebels.select(col("^.*_color$"))
let rebelQuotes = newDataFrame:
  quote: ["You know, sometimes I amaze myself.",
          "That doesn't sound too hard.",
          "I have a bad feeling about this."]

nbShow concat([rebelNames, rebelColors, rebelQuotes], how = Horizontal)
shape: (3, 5)
namehair_colorskin_coloreye_colorquote
strstrstrstrstr
"Han Solo""brown""fair""brown""You know, sometimes I amaze my…
"Leia Organa""brown""light""brown""That doesn't sound too hard."
"Luke Skywalker""blond""fair""blue""I have a bad feeling about thi…

Adding Row Indices

nbShow rebels.withRowIndex(name = "rebel_id", offset = 1)
shape: (3, 16)
rebel_idnameheightmasshair_colorskin_coloreye_colorbirth_yearsexgenderhomeworldspeciesvehiclesstarshipsbirth_datescreen_time
u32stru16f64strstrstrf64catcatstrstrlist[str]list[str]dateduration[ΞΌs]
1"Han Solo"18080.0"brown""fair""brown"29.0"male""masculine""Corellia""Human"null["Millennium Falcon", "Imperial shuttle"]1948-06-011h 12m 37s
2"Leia Organa"15049.0"brown""light""brown"19.0"female""feminine""Alderaan""Human"["Imperial Speeder Bike"]null1958-05-301h 3m 40s
3"Luke Skywalker"17277.0"blond""fair""blue"19.0"male""masculine""Tatooine""Human"["Snowspeeder", "Imperial Speeder Bike"]["X-wing", "Imperial shuttle"]1958-05-301h 58m 44s
import nanuqbook
bookInit()

nbText: "# Selecting and creating columns"

attribution definitiveGuide(10, "Selecting and Creating Columns",
  "The data is read from `data/definitive-guide/`. Python's column slices `rebels[:, :6]` " &
  "are `select`s by name here. Left out: selecting by position (`cs.by_index`), most of " &
  "combining selectors with set operations, the cells that the book shows raising an " &
  "error.")

nbText: """
Most of what you do to a frame comes down to two verbs: `select`, which keeps the columns
you name (and computes new ones), and `withColumns`, which keeps all the columns and adds
or replaces some. This chapter plays with both on a table of Star Wars characters, reduced
to three rebels.
"""

tabs """
import polars as pl

starwars = pl.read_parquet("data/definitive-guide/starwars.parquet")
rebels = starwars.drop("films").filter(
    pl.col("name").is_in(["Luke Skywalker", "Leia Organa", "Han Solo"])
)

rebels[:, :6]
""":
  nbCode:
    import nanuq

    let starwars = readParquet("data/definitive-guide/starwars.parquet")
    let rebels = starwars.drop("films").filter(
      col.name.isIn(["Luke Skywalker", "Leia Organa", "Han Solo"]))

    nbShow rebels.select(col("name", "height", "mass", "hair_color", "skin_color", "eye_color"))

tabs """
rebels[:, 6:11]
""":
  nbCode:
    nbShow rebels.select(col("birth_year", "sex", "gender", "homeworld", "species"))

tabs """
rebels[:, 11:]
""":
  nbCode:
    nbShow rebels.select(col("vehicles", "starships", "birth_date", "screen_time"))

nanuq """
Nanuq has no `df[rows, columns]` indexing: columns are picked by name with `select`.
The list columns, `vehicles` and `starships`, are `List(String)` columns.
"""

nbText: """
## Selecting Columns

`select` takes column names, `col` expressions, regular expressions on the names, and new
columns computed from the old ones:
"""

tabs """
rebels.select(
    "name",
    pl.col("homeworld"),
    pl.col("^.*_color$"),
    (pl.col("height") / 100).alias("height_m"),
)
""":
  nbCode:
    nbShow rebels.select(
      col.name,
      col.homeworld,
      col("^.*_color$"),
      (col.height / 100).alias("height_m"))

nanuq """
Nim's `select` takes expressions only, so a bare name is `col.name`. The height is a
`UInt16`; dividing it gives floats, with true division in Nanuq 0.3 as in Python.
"""

nbText: """
### Introducing Selectors

Selectors pick columns by name, type or position, and can be combined like sets.
"""

python """
import polars.selectors as cs

rebels.select(
    "name",
    cs.by_name("homeworld"),
    cs.matches("^.*_color$"),
    (cs.by_name("height") / 100).alias("height_m"),
)
"""

nanuq """
The book has `cs.by_name("^.*_color$")`, but since Python Polars 2.0 `by_name` takes
names only, not regular expressions, so this page uses `cs.matches`.
"""

nanuq """
Nanuq has no `polars.selectors` module. Its selectors are `col` with several names
(`col("a", "b")`), with Nim types (`col(string)`, `col(SomeNumber)`), with a regular
expression, and `all()`, which can `exclude` names. The cells below use them in place of
the `cs` functions.
"""

nbText: "### Selecting Based on Name"

tabs """
rebels.select(cs.starts_with("birth_"))
""":
  nbCode:
    nbShow rebels.select(col("^birth_.*$"))

tabs """
rebels.select(cs.ends_with("_color"))
""":
  nbCode:
    nbShow rebels.select(col("^.*_color$"))

tabs """
rebels.select(cs.contains("_"))
""":
  nbCode:
    nbShow rebels.select(col("^.*_.*$"))

tabs """
rebels.select(cs.matches("^[a-z]{4}$"))
""":
  nbCode:
    nbShow rebels.select(col("^[a-z]{4}$"))

nanuq """
A regular expression in `col` must match the whole name, from `^` to `$`; `starts_with`,
`ends_with` and `contains` become `^birth_.*$`, `^.*_color$` and `^.*_.*$`.
"""

nbText: "### Selecting Based on Data Type"

tabs """
rebels.group_by("hair_color").agg(cs.numeric().mean())
""":
  nbCode:
    nbShow rebels.groupBy(col.hair_color).agg(col(SomeNumber).mean)

tabs """
rebels.select(cs.string())
""":
  nbCode:
    nbShow rebels.select(col(string))

tabs """
rebels.select(cs.temporal())
""":
  nbCode:
    nbShow rebels.select(col(Date, Duration))

nanuq """
`cs.temporal()` is every date, time, datetime and duration column; in Nim you name the
types, `col(Date, Duration)`, with the `Duration` of `std/times`.
"""

tabs """
rebels.select(cs.by_dtype(pl.List(pl.String)))
""":
  nbCode:
    nbShow rebels.select(col(seq[string]))

nbText: """
### Selecting Based on Position

Python only: Nanuq has no `by_index`.
"""

python """
rebels.select("name", cs.by_index(range(-2, 0)))
"""

nbText: """
### Combining Selectors

Selectors combine with `|` (union), `&` (intersection), `-` (difference), `^` and `~`
(complement):
"""

python """
rebels.select(cs.by_name("hair_color") | cs.numeric())
"""

nanuq """
Nanuq's selectors have no set operations yet. Unions of types work, `col(float, int)`, and
so does a difference with names, `all().exclude("name")`; mixing names and types, as here,
does not.
"""

nbText: """
## Creating Columns

`withColumns` adds new columns, here the body mass index of each rebel:
"""

tabs """
rebels.with_columns(bmi=pl.col("mass") / ((pl.col("height") / 100) ** 2))
""":
  nbCode:
    nbShow rebels.withColumns((col.mass / pow(col.height / 100, 2)).alias("bmi"))

nanuq """
Python's keyword arguments, `bmi=...`, are `alias` in Nim; `**` is `pow`.
"""

nbText: "An expression on an existing column, without a new name, replaces it:"

tabs """
df = pl.DataFrame({"a": [1, 2, 3]})
df.with_columns(pl.col("a") * 2)
""":
  nbCode:
    let df = newDataFrame:
      a: [1, 2, 3]
    nbShow df.withColumns(col.a * 2)

tabs """
df.with_columns(a2=pl.col("a") * 2)
""":
  nbCode:
    nbShow df.withColumns((col.a * 2).alias("a2"))

nbText: """
Several columns at once. The second one is the rebels' age in whole years on the day
*Return of the Jedi* came out:
"""

tabs """
rebels.with_columns(
    bmi=pl.col("mass") / ((pl.col("height") / 100) ** 2),
    age_destroy=(
        (pl.date(1983, 5, 25) - pl.col("birth_date")).dt.total_days() / 365
    ).cast(pl.UInt8),
)
""":
  nbCode:
    nbShow rebels.withColumns(
      (col.mass / pow(col.height / 100, 2)).alias("bmi"),
      ((date(1983, 5, 25) - col.birth_date).dt.totalDays / 365).cast(uint8)
        .alias("age_destroy"))

nanuq """
`date(1983, 5, 25)` is a date literal in Nanuq 0.3. Subtracting a date column from it
gives a duration, and the `dt` namespace has `totalDays`.
"""

nbText: """
The columns in one `withColumns` are computed side by side, so one cannot use another:
the book shows that referring to `bmi` in the same call raises a `ColumnNotFoundError`,
and that two calls in a row work. The second call bins the BMI with `cut`:
"""

nanuq """
Nanuq's `cut` makes a Categorical column, like Python's.
"""

tabs """
(
    rebels.with_columns(
        bmi=pl.col("mass") / ((pl.col("height") / 100) ** 2)
    ).with_columns(
        bmi_cat=pl.col("bmi").cut(
            [18.5, 25], labels=["Underweight", "Normal", "Overweight"]
        )
    )
)
""":
  nbCode:
    nbShow rebels.withColumns(
        (col.mass / pow(col.height / 100, 2)).alias("bmi")
      ).withColumns(
        col.bmi.cut([18.5, 25], labels = ["Underweight", "Normal", "Overweight"])
          .alias("bmi_cat"))

nbText: "`select` creates columns too. The five characters with the highest BMI:"

tabs """
(
    starwars.select(
        "name",
        (pl.col("mass") / ((pl.col("height") / 100) ** 2)).alias("bmi"),
        "species",
    )
    .drop_nulls()
    .top_k(5, by="bmi")
)
""":
  nbCode:
    nbShow starwars.select(
        col.name,
        (col.mass / pow(col.height / 100, 2)).alias("bmi"),
        col.species)
      .dropNulls()
      .topK(5, by = "bmi")

nbText: "A literal is broadcast to every row:"

tabs """
df.with_columns(pl.lit(1).alias("ones"))
""":
  nbCode:
    nbShow df.withColumns(lit(1).alias("ones"))

tabs """
df.select(pl.all(), pl.lit(1).alias("ones"))
""":
  nbCode:
    nbShow df.select(all(), lit(1).alias("ones"))

nbText: """
## Related Column Operations

### Dropping

With `strict=False`, names that are not in the frame (here `screen_time` is, but it
need not be) are ignored:
"""

tabs """
rebels.drop("name", "screen_time", strict=False)
""":
  nbCode:
    nbShow rebels.drop(["name", "screen_time"], strict = false)

tabs """
rebels.select(~cs.by_name("name", "screen_time"))
""":
  nbCode:
    nbShow rebels.select(all().exclude("name", "screen_time"))

tabs """
rebels.select(cs.exclude("name", "screen_time"))
""":
  nbCode:
    nbShow rebels.select(all().exclude("name", "screen_time"))

nbText: "### Renaming"

tabs """
(
    rebels.rename({"homeworld": "planet", "mass": "weight"})
    .rename(lambda s: s.removesuffix("_color"))
    .select("name", "planet", "weight", "hair", "skin", "eye")
)
""":
  nbCode:
    nbShow rebels.rename({"homeworld": "planet", "mass": "weight"})
      .rename({"hair_color": "hair", "skin_color": "skin", "eye_color": "eye"})
      .select(col("name", "planet", "weight", "hair", "skin", "eye"))

nanuq """
`rename` takes a mapping, written with Nim's table constructor `{"a": "b"}`, but not a
function of the old name yet, so the second call names the three columns.
"""

nbText: "### Stacking"

tabs """
rebel_names = rebels.select("name")
rebel_colors = rebels.select(cs.ends_with("_color"))
rebel_quotes = pl.Series(
    "quote",
    [
        "You know, sometimes I amaze myself.",
        "That doesn't sound too hard.",
        "I have a bad feeling about this.",
    ],
)

(rebel_names.hstack(rebel_colors).hstack([rebel_quotes]))
""":
  nbCode:
    let rebelNames = rebels.select(col.name)
    let rebelColors = rebels.select(col("^.*_color$"))
    let rebelQuotes = newDataFrame:
      quote: ["You know, sometimes I amaze myself.",
              "That doesn't sound too hard.",
              "I have a bad feeling about this."]

    nbShow concat([rebelNames, rebelColors, rebelQuotes], how = Horizontal)

nanuq """
Nanuq has no `hstack`: a horizontal `concat` of frames does the same.
"""

nbText: "### Adding Row Indices"

tabs """
rebels.with_row_index(name="rebel_id", offset=1)
""":
  nbCode:
    nbShow rebels.withRowIndex(name = "rebel_id", offset = 1)

bookSave()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.