Sub topic 1
DataFrames and Expressions: The Basic Containers
Prerequisites
Assume you know basic Python lists, dictionaries, functions, and method chaining. You should also recognize rows, columns, and CSV files.
DataFrames and Series
A Polars DataFrame is a table with named columns. A Series is one typed column. Each column can have its own data type, such as String, Int64, or Float64.
Create a DataFrame from a dictionary whose values are column data:
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy"],
"dept": ["eng", "eng", "ops"],
"salary": [120, 100, 80],
}
)
print(df)
print(df["salary"]) # A Series
print(df.schema)The schema maps each column name to its data type. Inspect it before writing transformations. Unexpected types, such as numbers read as strings, often explain failed comparisons or calculations.
Expressions and Contexts
An expression is a description of a computation. pl.col("salary") refers to the salary column. Arithmetic and comparisons build new expressions:
result = (
df.with_columns(
(pl.col("salary") / 12).alias("monthly_salary"),
(pl.col("salary") >= 100).alias("is_high"),
)
.filter(pl.col("salary") > 80)
.select("name", "monthly_salary", "is_high")
)
print(result)The same expression can produce different results depending on its context:
| Context | Purpose | Result |
|---|---|---|
| `select` | Choose or compute columns | A new table containing the selected results |
| `with_columns` | Add or replace columns | The original columns plus derived columns |
| `filter` | Keep matching rows | A table containing rows where the condition is true |
alias gives a computed expression a column name. Without it, Polars may generate a less useful name.
Exercise
Which context should you use to keep only employees whose salary is at least 100?
Show answer
Use filter: df.filter(pl.col("salary") >= 100).