PolarsのExpression
同じExpressionでも、異なるcontextに応じて異なる結果になる
遅延評価される
実行前に良い感じに最適化されるために高速になるらしい ref こういう、直観どおりの計算式のこと
code:py
pl.col("weight") / (pl.col("height") ** 2)
Expression expansion
以下2つは同じ意味
code:py
pl.col("weight", "height").mean().name.prefix("avg_")
code:py
[
pl.col("weight").mean().alias("avg_weight"),
pl.col("height").mean().alias("avg_height"),
]
code:py
out = df.select(
pl.col("integers").cast(pl.String),
pl.col("float").cast(pl.String),
pl.col("floats_as_string").cast(pl.Float64),
)
strict
defaultはtrue
変換できないときはエラーにする
falseにすると
変換できないときはnullになる
文字列操作
.str
code:py
out = df.select(
pl.col("animal"),
pl.col("animal").str.contains("cat|bit").alias("regex"),
pl.col("animal").str.contains("rab$", literal=True).alias("literal"),
pl.col("animal").str.starts_with("rab").alias("starts_with"),
pl.col("animal").str.ends_with("dog").alias("ends_with"),
)
str.extract
str.extract_all
str.replace
str.replace_all
categorical
カラムの内容が、赤、黄、青、みたいに決まったカテゴリに限るやつの扱い
内部で辞書を作るので、普通に文字列を使うより高速らしい
2種類
Enum
事前にカテゴリが決まっているもの
Categorical
カテゴリが不明または固定されていないもの
aggregation
code:py
def compute_age():
return date.today().year - pl.col("birthday").dt.year()
def avg_birthday(gender: str) -> pl.Expr:
return (
compute_age()
.filter(pl.col("gender") == gender)
.mean()
.alias(f"avg {gender} birthday")
)
q = (
dataset.lazy()
.group_by("state")
.agg(
avg_birthday("M"),
avg_birthday("F"),
(pl.col("gender") == "M").sum().alias("# male"),
(pl.col("gender") == "F").sum().alias("# female"),
)
.limit(5)
)
欠損値
各カラムの欠損値の数
欠損データの補完
code:py
pl.col("col2").fill_null(pl.lit(2)) # リテラルで補完
pl.col("col2").fill_null(strategy="forward") # strategy
pl.col("col2").fill_null(pl.median("col2")) # 式で補完
pl.col("col2").interpolate() # 補間で補完
NaN
欠損データ(null)とは区別される
Expressions
Window functions
Folds
Lists and Arrays
Expression plugins
User-defined functions (Python)
The Struct datatype
Numpy