Getting started

The first chapter of the cookbook introduces the three building blocks of Polars, DataFrame, Series and LazyFrame, then the everyday moves: selecting, filtering, adding columns and chaining it all together. Most of it is on the Titanic passenger list.

The Polars DataFrame

A DataFrame is a table of named columns, each with one data type. You can build one from literal data:

import nanuq

var df = newDataFrame:
  nums: [1, 2, 3, 4, 5]
  letters: ["a", "b", "c", "d", "e"]
nbShow df.head()
shape: (5, 2)
numsletters
i64str
1"a"
2"b"
3"c"
4"d"
5"e"

Or read it from a file:

df = readCsv("data/polars-cookbook/titanic_dataset.csv")
nbShow df.head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"

A frame knows its schema, its column names and types, and its shape:

echo df.schema
{"PassengerId": Int64, "Survived": Int64, "Pclass": Int64, "Name": String, "Sex": String, "Age": Float64, "SibSp": Int64, "Parch": Int64, "Ticket": String, "Fare": Float64, "Cabin": String, "Embarked": String}
echo df.columns
@["PassengerId", "Survived", "Pclass", "Name", "Sex", "Age", "SibSp", "Parch", "Ticket", "Fare", "Cabin", "Embarked"]
echo df.dtypes
@[Int64, Int64, Int64, String, String, Float64, Int64, Int64, String, Float64, String, String]
echo df.shape
(891, 12)
echo df.height
891
echo df.width
12

The Polars Series

A Series is one named column: one dimension, one data type. You can build one directly:

let s = series("col", [1, 2, 3, 4, 5])
nbShow s.head.toFrame
shape: (5, 1)
col
i64
1
2
3
4
5

or take one out of a frame: to_series takes a column by position (the first by default), get_column by name.

let data = newDataFrame:
  a: [1, 2, 3]
  b: [4, 5, 6]
let sA = data.toSeries()
nbShow sA.head.toFrame
shape: (3, 1)
a
i64
1
2
3
let sB = data.toSeries(1)
nbShow sB.head.toFrame
shape: (3, 1)
b
i64
4
5
6
let sB2 = data.getColumn("b")
nbShow sB2.head.toFrame
shape: (3, 1)
b
i64
4
5
6

A Series knows its length, its name and its data type:

echo s.len
echo s.name
echo s.dtype
5
col
Int64

The Polars LazyFrame

A LazyFrame is a query plan: nothing is computed until you collect it, which lets Polars optimize the whole query first.

let names = newDataFrame:
  name: ["Sarah", "Mike", "Bob", "Ashley"]
nbShow names.lazy.collect.head()
shape: (4, 1)
name
str
"Sarah"
"Mike"
"Bob"
"Ashley"

scanCsv reads a file lazily:

let lf = scanCsv("data/polars-cookbook/titanic_dataset.csv")
nbShow lf.head().collect
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"
nbShow df.lazy.head(3).collect
shape: (3, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"

A LazyFrame can tell its schema without reading the data:

echo lf.collectSchema
{"PassengerId": Int64, "Survived": Int64, "Pclass": Int64, "Name": String, "Sex": String, "Age": Float64, "SibSp": Int64, "Parch": Int64, "Ticket": String, "Fare": Float64, "Cabin": String, "Embarked": String}
echo lf.collectSchema.len
12

explain shows the plan Polars will run. Only the two selected columns are read from the file, as the projection 2/12 COLUMNS shows.

echo lf.select(col("Name", "Age")).explain
Csv SCAN [data/polars-cookbook/titanic_dataset.csv]
PROJECT 2/12 COLUMNS
ESTIMATED ROWS: 971

Selecting columns and filtering data

select picks columns, by name or by expression:

nbShow df.select(col(["Survived", "Ticket", "Fare"])).head()
shape: (5, 3)
SurvivedTicketFare
i64strf64
0"A/5 21171"7.25
1"PC 17599"71.2833
1"STON/O2. 3101282"7.925
1"113803"53.1
0"373450"8.05
nbShow df.select(col.Survived, col.Ticket, col.Fare).head()
shape: (5, 3)
SurvivedTicketFare
i64strf64
0"A/5 21171"7.25
1"PC 17599"71.2833
1"STON/O2. 3101282"7.925
1"113803"53.1
0"373450"8.05

withColumns keeps all the columns and adds (or replaces) the ones you give, so with existing columns it changes nothing:

nbShow df.withColumns(col.Survived, col.Ticket, col.Fare).head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"

filter keeps the rows where a condition holds:

nbShow df.filter(col.Age >= 30).head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"
701"McCarthy, Mr. Timothy J""male"54.000"17463"51.8625"E46""S"
1211"Bonnell, Miss. Elizabeth""female"58.000"113783"26.55"C103""S"
nbShow df.filter(col.Age >= 30 and col.Sex == "male").head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"
701"McCarthy, Mr. Timothy J""male"54.000"17463"51.8625"E46""S"
1403"Andersson, Mr. Anders Johan""male"39.015"347082"31.275null"S"
2102"Fynney, Mr. Joseph J""male"35.000"239865"26.0null"S"
2212"Beesley, Mr. Lawrence""male"34.000"248698"13.0"D56""S"

Columns can also be picked by a regular expression on their names, or by type:

nbShow df.select(col("^[a-zA-Z]{0,4}$")).head()
shape: (5, 4)
NameSexAgeFare
strstrf64f64
"Braund, Mr. Owen Harris""male"22.07.25
"Cumings, Mrs. John Bradley (Fl…"female"38.071.2833
"Heikkinen, Miss. Laina""female"26.07.925
"Futrelle, Mrs. Jacques Heath (…"female"35.053.1
"Allen, Mr. William Henry""male"35.08.05
nbShow df.select(col(string)).head()
shape: (5, 5)
NameSexTicketCabinEmbarked
strstrstrstrstr
"Braund, Mr. Owen Harris""male""A/5 21171"null"S"
"Cumings, Mrs. John Bradley (Fl…"female""PC 17599""C85""C"
"Heikkinen, Miss. Laina""female""STON/O2. 3101282"null"S"
"Futrelle, Mrs. Jacques Heath (…"female""113803""C123""S"
"Allen, Mr. William Henry""male""373450"null"S"
nbShow df.select(col(SomeNumber)).head()
shape: (5, 7)
PassengerIdSurvivedPclassAgeSibSpParchFare
i64i64i64f64i64i64f64
10322.0107.25
21138.01071.2833
31326.0007.925
41135.01053.1
50335.0008.05
nbShow df.select(col("^.*(se|ed).*$")).head()
shape: (5, 3)
PassengerIdSurvivedEmbarked
i64i64str
10"S"
21"C"
31"S"
41"S"
50"S"

Creating, modifying, and deleting columns

An aggregation in withColumns is broadcast to every row:

nbShow df.withColumns(col.Fare.max.alias("Max Fare")).head()
shape: (5, 13)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedMax Fare
i64i64i64strstrf64i64i64strf64strstrf64
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"512.3292
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"512.3292
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"512.3292
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"512.3292
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"512.3292
nbShow df.withColumns((col.Fare.max - col.Fare.mean).alias("Max Fare - Avg Fare")).head()
shape: (5, 13)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedMax Fare - Avg Fare
i64i64i64strstrf64i64i64strf64strstrf64
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"480.124992
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"480.124992
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"480.124992
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"480.124992
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"480.124992

A literal gets the name literal, unless you alias it:

nbShow df.withColumns(lit("Titanic")).head()
shape: (5, 13)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedliteral
i64i64i64strstrf64i64i64strf64strstrstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S""Titanic"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C""Titanic"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S""Titanic"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S""Titanic"
503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S""Titanic"
nbShow df.withRowIndex().head()
shape: (5, 13)
indexPassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
u32i64i64i64strstrf64i64i64strf64strstr
0103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"7.25null"S"
1211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"71.2833"C85""C"
2313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"7.925null"S"
3411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"53.1"C123""S"
4503"Allen, Mr. William Henry""male"35.000"373450"8.05null"S"

An expression on an existing column replaces it:

nbShow df.withColumns(col.Sex.str.toTitlecase).head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""Male"22.010"A/5 21171"7.25null"S"
211"Cumings, Mrs. John Bradley (Fl…"Female"38.010"PC 17599"71.2833"C85""C"
313"Heikkinen, Miss. Laina""Female"26.000"STON/O2. 3101282"7.925null"S"
411"Futrelle, Mrs. Jacques Heath (…"Female"35.010"113803"53.1"C123""S"
503"Allen, Mr. William Henry""Male"35.000"373450"8.05null"S"
nbShow df.withColumns(col.Fare.max).head()
shape: (5, 12)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarked
i64i64i64strstrf64i64i64strf64strstr
103"Braund, Mr. Owen Harris""male"22.010"A/5 21171"512.3292null"S"
211"Cumings, Mrs. John Bradley (Fl…"female"38.010"PC 17599"512.3292"C85""C"
313"Heikkinen, Miss. Laina""female"26.000"STON/O2. 3101282"512.3292null"S"
411"Futrelle, Mrs. Jacques Heath (…"female"35.010"113803"512.3292"C123""S"
503"Allen, Mr. William Henry""male"35.000"373450"512.3292null"S"

To delete columns, drop them, or select the ones to keep:

nbShow df.drop(["Pclass", "Name", "SibSp", "Parch", "Ticket", "Cabin", "Embarked"]).head()
shape: (5, 5)
PassengerIdSurvivedSexAgeFare
i64i64strf64f64
10"male"22.07.25
21"female"38.071.2833
31"female"26.07.925
41"female"35.053.1
50"male"35.08.05
nbShow df.select(col(["PassengerId", "Survived", "Sex", "Age", "Fare"])).head()
shape: (5, 5)
PassengerIdSurvivedSexAgeFare
i64i64strf64f64
10"male"22.07.25
21"female"38.071.2833
31"female"26.07.925
41"female"35.053.1
50"male"35.08.05

Several new columns in one withColumns are computed in parallel; a chain of withColumns runs them one after the other. Both give the same table:

let bestPractice = df.withColumns(
  col.Fare.max.alias("Max Fare"),
  lit("Titanic"),
  col.Sex.str.toTitlecase)
nbShow bestPractice.head()
shape: (5, 14)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedMax Fareliteral
i64i64i64strstrf64i64i64strf64strstrf64str
103"Braund, Mr. Owen Harris""Male"22.010"A/5 21171"7.25null"S"512.3292"Titanic"
211"Cumings, Mrs. John Bradley (Fl…"Female"38.010"PC 17599"71.2833"C85""C"512.3292"Titanic"
313"Heikkinen, Miss. Laina""Female"26.000"STON/O2. 3101282"7.925null"S"512.3292"Titanic"
411"Futrelle, Mrs. Jacques Heath (…"Female"35.010"113803"53.1"C123""S"512.3292"Titanic"
503"Allen, Mr. William Henry""Male"35.000"373450"8.05null"S"512.3292"Titanic"
let notSoGoodPractice = df
  .withColumns(col.Fare.max.alias("Max Fare"))
  .withColumns(lit("Titanic"))
  .withColumns(col.Sex.str.toTitlecase)
nbShow notSoGoodPractice.head()
shape: (5, 14)
PassengerIdSurvivedPclassNameSexAgeSibSpParchTicketFareCabinEmbarkedMax Fareliteral
i64i64i64strstrf64i64i64strf64strstrf64str
103"Braund, Mr. Owen Harris""Male"22.010"A/5 21171"7.25null"S"512.3292"Titanic"
211"Cumings, Mrs. John Bradley (Fl…"Female"38.010"PC 17599"71.2833"C85""C"512.3292"Titanic"
313"Heikkinen, Miss. Laina""Female"26.000"STON/O2. 3101282"7.925null"S"512.3292"Titanic"
411"Futrelle, Mrs. Jacques Heath (…"Female"35.010"113803"53.1"C123""S"512.3292"Titanic"
503"Allen, Mr. William Henry""Male"35.000"373450"8.05null"S"512.3292"Titanic"

Method chaining

Each method returns a new frame, so the steps of an analysis can be written one per line or chained into a single expression.

let cols = ["Name", "Sex", "Age", "Fare", "Cabin", "Pclass", "Survived"]

var steps = df.select(col(cols))
steps = steps.filter(col.Age >= 35)
steps = steps.sort(["Age", "Name"])
nbShow steps.head()
shape: (5, 7)
NameSexAgeFareCabinPclassSurvived
strstrf64f64stri64i64
"Abbott, Mrs. Stanton (Rosa Hun…"female"35.020.25null31
"Allen, Mr. William Henry""male"35.08.05null30
"Asim, Mr. Adola""male"35.07.05null30
"Bissette, Miss. Amelia""female"35.0135.6333"C99"11
"Brocklebank, Mr. William Alfre…"male"35.08.05null30
let chained = df
  .select(col(cols))
  .filter(col.Age >= 35)
  .sort(["Age", "Name"])
nbShow chained.head()
shape: (5, 7)
NameSexAgeFareCabinPclassSurvived
strstrf64f64stri64i64
"Abbott, Mrs. Stanton (Rosa Hun…"female"35.020.25null31
"Allen, Mr. William Henry""male"35.08.05null30
"Asim, Mr. Adola""male"35.07.05null30
"Bissette, Miss. Amelia""female"35.0135.6333"C99"11
"Brocklebank, Mr. William Alfre…"male"35.08.05null30
import nanuqbook
bookInit()

nbText: "# Getting started"

attribution polarsCookbook(1, "Getting Started with Python Polars",
  "Data is read from `data/polars-cookbook/`. Left out: `from_numpy`, " &
  "`flags`, `show_graph` (it draws the query plan with Graphviz), and the recipe on " &
  "data larger than memory, which needs a Chicago taxi trips file that the book does not ship.")

nbText: """
The first chapter of the cookbook introduces the three building blocks of Polars,
DataFrame, Series and LazyFrame, then the everyday moves: selecting, filtering, adding
columns and chaining it all together. Most of it is on the Titanic passenger list.

## The Polars DataFrame

A DataFrame is a table of named columns, each with one data type. You can build one from
literal data:
"""

tabs """
import polars as pl

df = pl.DataFrame({
    'nums': [1,2,3,4,5],
    'letters': ['a','b','c','d','e']
})
df.head()
""":
  nbCode:
    import nanuq

    var df = newDataFrame:
      nums: [1, 2, 3, 4, 5]
      letters: ["a", "b", "c", "d", "e"]
    nbShow df.head()

nbText: "Or read it from a file:"

tabs """
df = pl.read_csv('data/polars-cookbook/titanic_dataset.csv')
df.head()
""":
  nbCode:
    df = readCsv("data/polars-cookbook/titanic_dataset.csv")
    nbShow df.head()

nbText: "A frame knows its schema, its column names and types, and its shape:"

tabs """
df.schema
""":
  nbCode:
    echo df.schema

tabs """
df.columns
""":
  nbCode:
    echo df.columns

tabs """
df.dtypes
""":
  nbCode:
    echo df.dtypes

tabs """
df.shape
""":
  nbCode:
    echo df.shape

tabs """
df.height
""":
  nbCode:
    echo df.height

tabs """
df.width
""":
  nbCode:
    echo df.width

nanuq """
The recipe also shows `df.flags` (which columns Polars knows to be sorted) and
`pl.from_numpy`. Nanuq has neither: in Nim you build a frame from sequences.
"""

nbText: """
## The Polars Series

A Series is one named column: one dimension, one data type. You can build one directly:
"""

nanuq """
Nanuq shows a Series as a one-column frame (`toFrame`), so the Python side does too
(`to_frame`).
"""

tabs """
s = pl.Series('col', [1,2,3,4,5])
s.head().to_frame()
""":
  nbCode:
    let s = series("col", [1, 2, 3, 4, 5])
    nbShow s.head.toFrame

nbText: """
or take one out of a frame: `to_series` takes a column by position (the first by
default), `get_column` by name.
"""

tabs """
data = {'a': [1,2,3], 'b': [4,5,6]}
s_a = (
    pl.DataFrame(data)
    .to_series()
)
s_a.head().to_frame()
""":
  nbCode:
    let data = newDataFrame:
      a: [1, 2, 3]
      b: [4, 5, 6]
    let sA = data.toSeries()
    nbShow sA.head.toFrame

tabs """
s_b = (
    pl.DataFrame(data)
    .to_series(1)
)
s_b.head().to_frame()
""":
  nbCode:
    let sB = data.toSeries(1)
    nbShow sB.head.toFrame

nanuq """
`data.getColumn("b")` can also be written `data["b"]`, as in Python.
"""

tabs """
s_b2 = (
    pl.DataFrame(data)
    .get_column('b')
)
s_b2.head().to_frame()
""":
  nbCode:
    let sB2 = data.getColumn("b")
    nbShow sB2.head.toFrame

nbText: """
A Series knows its length, its name and its data type:
"""

nanuq """
A Series has one dimension, so where Python's `shape` is the tuple `(5,)`, Nanuq has
`len`. A data type prints the way you write it in Nim, so `Int64` here matches Python.
"""

tabs """
print(s.shape)
print(s.name)
print(s.dtype)
""":
  nbCode:
    echo s.len
    echo s.name
    echo s.dtype

nbText: """
## The Polars LazyFrame

A LazyFrame is a query plan: nothing is computed until you `collect` it, which lets Polars
optimize the whole query first.
"""

tabs """
data = {'name': ['Sarah',  'Mike', 'Bob', 'Ashley']}
lf = pl.LazyFrame(data)
lf.collect().head()
""":
  nbCode:
    let names = newDataFrame:
      name: ["Sarah", "Mike", "Bob", "Ashley"]
    nbShow names.lazy.collect.head()

nanuq """
Nanuq has no `LazyFrame` constructor from data: you build a DataFrame and call `lazy` on
it.
"""

nbText: "`scanCsv` reads a file lazily:"

tabs """
lf = pl.scan_csv('data/polars-cookbook/titanic_dataset.csv')
lf.head().collect()
""":
  nbCode:
    let lf = scanCsv("data/polars-cookbook/titanic_dataset.csv")
    nbShow lf.head().collect

tabs """
df.lazy().head(3).collect()
""":
  nbCode:
    nbShow df.lazy.head(3).collect

nbText: "A LazyFrame can tell its schema without reading the data:"

tabs """
lf.collect_schema()
""":
  nbCode:
    echo lf.collectSchema

tabs """
lf.collect_schema().len()
""":
  nbCode:
    echo lf.collectSchema.len

nbText: """
`explain` shows the plan Polars will run. Only the two selected columns are read from the
file, as the projection `2/12 COLUMNS` shows.
"""

tabs """
print(
    lf
    .select(pl.col('Name', 'Age'))
    .explain()
    , sep='\n'
)
""":
  nbCode:
    echo lf.select(col("Name", "Age")).explain

nanuq """
The recipe also draws the plan with `show_graph`, which needs Graphviz. Nanuq has no
`show_graph`.
"""

nbText: """
## Selecting columns and filtering data

`select` picks columns, by name or by expression:
"""

tabs """
df.select(pl.col(['Survived', 'Ticket', 'Fare'])).head()
""":
  nbCode:
    nbShow df.select(col(["Survived", "Ticket", "Fare"])).head()

tabs """
df.select(
    pl.col('Survived'),
    pl.col('Ticket'),
    pl.col('Fare')
).head()
""":
  nbCode:
    nbShow df.select(col.Survived, col.Ticket, col.Fare).head()

nbText: """
`withColumns` keeps all the columns and adds (or replaces) the ones you give, so with
existing columns it changes nothing:
"""

tabs """
df.with_columns(
    pl.col('Survived'),
    pl.col('Ticket'),
    pl.col('Fare')
).head()
""":
  nbCode:
    nbShow df.withColumns(col.Survived, col.Ticket, col.Fare).head()

nanuq """
Python's `select` and `with_columns` also take bare column names (`df.select(['Survived',
'Ticket', 'Fare'])`); Nim's take expressions, so names go through `col`.
"""

nbText: "`filter` keeps the rows where a condition holds:"

tabs """
df.filter((pl.col('Age') >= 30)).head()
""":
  nbCode:
    nbShow df.filter(col.Age >= 30).head()

tabs """
df.filter(
    (pl.col('Age') >= 30) & (pl.col('Sex')=='male')
).head()
""":
  nbCode:
    nbShow df.filter(col.Age >= 30 and col.Sex == "male").head()

nbText: """
Columns can also be picked by a regular expression on their names, or by type:
"""

tabs """
df.select(pl.col('^[a-zA-Z]{0,4}$')).head()
""":
  nbCode:
    nbShow df.select(col("^[a-zA-Z]{0,4}$")).head()

tabs """
df.select(pl.col(pl.String)).head()
""":
  nbCode:
    nbShow df.select(col(string)).head()

tabs """
import polars.selectors as cs

df.select(cs.numeric()).head()
""":
  nbCode:
    nbShow df.select(col(SomeNumber)).head()

tabs """
df.select(cs.matches('se|ed')).head()
""":
  nbCode:
    nbShow df.select(col("^.*(se|ed).*$")).head()

nanuq """
Nanuq has no `polars.selectors` module: Polars' selectors are `col` with a Nim type or
typeclass (`col(SomeNumber)` for `cs.numeric()`) or a regular expression. `cs.matches`
looks for the pattern anywhere in the name; `col` takes a whole-name regex between `^` and
`$`. Python's `df[['Age', 'Sex']]` indexing is `select` in Nim.
"""

nbText: """
## Creating, modifying, and deleting columns

An aggregation in `withColumns` is broadcast to every row:
"""

tabs """
df.with_columns(
    pl.col('Fare').max().alias('Max Fare')
).head()
""":
  nbCode:
    nbShow df.withColumns(col.Fare.max.alias("Max Fare")).head()

tabs """
df.with_columns(
    (pl.col('Fare').max() - pl.col('Fare').mean()).alias('Max Fare - Avg Fare')
).head()
""":
  nbCode:
    nbShow df.withColumns((col.Fare.max - col.Fare.mean).alias("Max Fare - Avg Fare")).head()

nbText: "A literal gets the name `literal`, unless you alias it:"

tabs """
df.with_columns(pl.lit('Titanic')).head()
""":
  nbCode:
    nbShow df.withColumns(lit("Titanic")).head()

tabs """
df.with_row_index().head()
""":
  nbCode:
    nbShow df.withRowIndex().head()

nbText: "An expression on an existing column replaces it:"

tabs """
df.with_columns(pl.col('Sex').str.to_titlecase()).head()
""":
  nbCode:
    nbShow df.withColumns(col.Sex.str.toTitlecase).head()

nanuq """
`toTitlecase` is new in Nanuq 0.3, and needs Polars' `nightly` feature: the release
libraries have it, while a library built from source with stable Rust raises an
`InvalidOperationError`.
"""

tabs """
df.with_columns(
    pl.col('Fare').max()
).head()
""":
  nbCode:
    nbShow df.withColumns(col.Fare.max).head()

nbText: "To delete columns, `drop` them, or `select` the ones to keep:"

tabs """
df.drop(['Pclass', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked']).head()
""":
  nbCode:
    nbShow df.drop(["Pclass", "Name", "SibSp", "Parch", "Ticket", "Cabin", "Embarked"]).head()

tabs """
df.select(['PassengerId', 'Survived', 'Sex', 'Age', 'Fare']).head()
""":
  nbCode:
    nbShow df.select(col(["PassengerId", "Survived", "Sex", "Age", "Fare"])).head()

nbText: """
Several new columns in one `withColumns` are computed in parallel; a chain of
`withColumns` runs them one after the other. Both give the same table:
"""

tabs """
best_practice = (
    df.with_columns(
        pl.col('Fare').max().alias('Max Fare'),
        pl.lit('Titanic'),
        pl.col('Sex').str.to_titlecase()
    )
)
best_practice.head()
""":
  nbCode:
    let bestPractice = df.withColumns(
      col.Fare.max.alias("Max Fare"),
      lit("Titanic"),
      col.Sex.str.toTitlecase)
    nbShow bestPractice.head()

tabs """
not_so_good_practice = (
    df
    .with_columns(pl.col('Fare').max().alias('Max Fare'))
    .with_columns(pl.lit('Titanic'))
    .with_columns(pl.col('Sex').str.to_titlecase())
)
not_so_good_practice.head()
""":
  nbCode:
    let notSoGoodPractice = df
      .withColumns(col.Fare.max.alias("Max Fare"))
      .withColumns(lit("Titanic"))
      .withColumns(col.Sex.str.toTitlecase)
    nbShow notSoGoodPractice.head()

nbText: """
## Method chaining

Each method returns a new frame, so the steps of an analysis can be written one per line
or chained into a single expression.
"""

tabs """
cols = ['Name', 'Sex', 'Age', 'Fare', 'Cabin', 'Pclass', 'Survived']

df = df.select(cols)
df = df.filter(pl.col('Age')>=35)
df = df.sort(by=['Age', 'Name'])
df.head()
""":
  nbCode:
    let cols = ["Name", "Sex", "Age", "Fare", "Cabin", "Pclass", "Survived"]

    var steps = df.select(col(cols))
    steps = steps.filter(col.Age >= 35)
    steps = steps.sort(["Age", "Name"])
    nbShow steps.head()

tabs """
df = pl.read_csv('data/polars-cookbook/titanic_dataset.csv')
df = (
    df
    .select(cols)
    .filter(pl.col('Age')>=35)
    .sort(by=['Age', 'Name'])
)
df.head()
""":
  nbCode:
    let chained = df
      .select(col(cols))
      .filter(col.Age >= 35)
      .sort(["Age", "Name"])
    nbShow chained.head()

nanuq """
Nim's `select` takes expressions, so the list of names goes through `col`, which takes an
array (or a `seq`) of names since Nanuq 0.3.
"""

nanuq """
Nim's method call syntax chains without the parentheses Python needs: a line that starts
with `.` continues the expression above it.
"""

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