has an intuitive and concise API (if you know Polars already)
has dataframe friendly design
and covers a wide variety of data science topics, such as simple statistics, linear regression, string edit distances, tabular data transforms, feature extraction, traditional modelling pipelines, model evaluation metrics, etc., etc..
It stands on the shoulders of the great Polars dataframe. You can see examples. Here are some highlights!
Parallel ML Metrics Calculation
import polars as pl
import polars_ds as pds
# Parallel evaluation of multiple ML metrics on different segments of data
df.lazy().group_by("segments").agg(
# any other metrics you want in here
pds.query_roc_auc("actual", "predicted").alias("roc_auc"),
pds.query_log_loss("actual", "predicted").alias("log_loss"),
).collect()
shape: (2, 3)
┌──────────┬──────────┬──────────┐
│ segments ┆ roc_auc ┆ log_loss │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞══════════╪══════════╪══════════╡
│ a ┆ 0.497745 ┆ 1.006438 │
│ b ┆ 0.498801 ┆ 0.997226 │
└──────────┴──────────┴──────────┘
Quick and simple modeling on the fly (non-persistent)
E.g. running a quick linear regression and see the predictions and residues:
import polars as pl
import polars.selectors as cs
from polars_ds.pipeline import Pipeline, Blueprint
bp = (
Blueprint(df, name = "example", target = "approved", lowercase=True) # You can optionally
.filter(pl.col("city_category").is_not_null())
.linear_impute(features = ["var1", "existing_emi"], target = "loan_period")
.impute(["existing_emi"], method = "median")
.append_expr( # generate some features
pl.col("existing_emi").log1p().alias("existing_emi_log1p"),
pl.col("loan_amount").log1p().alias("loan_amount_log1p"),
pl.col("loan_amount").clip(lower_bound = 0, upper_bound = 1000).alias("loan_amount_clipped"),
pl.col("loan_amount").sqrt().alias("loan_amount_sqrt"),
pl.col("loan_amount").shift(-1).alias("loan_amount_lead_1") # shift(-1) is a lead transform
)
.scale( # target is numerical, but will be excluded automatically because bp is initialzied with a target
cs.numeric().exclude(["var1", "existing_emi_log1p"]), method = "standard"
) # Scale the columns up to this point. The columns below won't be scaled
.append_expr(
# Add missing flags
pl.col("employer_category1").is_null().cast(pl.UInt8).alias("employer_category1_is_missing")
)
.one_hot_encode("gender", drop_first=True)
.woe_encode("city_category") # No need to specify target because we initialized bp with a target
.target_encode("employer_category1", min_samples_leaf = 20, smoothing = 10.0) # same as above
)
print(bp)
pipe:Pipeline = bp.materialize()
# Check out the result in our example notebooks! (examples/pipeline.ipynb)
df_transformed = pipe.transform(df)
df_transformed.head()
Since Polars >=1.34 supports collect_batches(), you can also use this to perform batched machine learning
for df_batch in pipe.transform(df, return_lazy=True).collect_batches():
X_batch, y_batch = your_function_to_turn_df_batch_into_model_inputs(df_batch)
ml_model.update(X_batch, y_batch)
Get all neighbors within radius r, call them best friends, and count the number. Due to limitations,
this currently doesn't preserve the index, and is not fast when k or dimension of data is large.
df.select(
pl.col("id"),
pds.query_radius_ptwise(
pl.col("var1"), pl.col("var2"), pl.col("var3"), # Columns used as the coordinates in 3d space
index = pl.col("id"),
r = 0.1,
dist = "sql2", # squared l2
parallel = True
).alias("best friends"),
).with_columns( # -1 to remove the point itself
(pl.col("best friends").list.len() - 1).alias("best friends count")
).head()
shape: (5, 3)
┌─────┬───────────────────┬────────────────────┐
│ id ┆ best friends ┆ best friends count │
│ --- ┆ --- ┆ --- │
│ u32 ┆ list[u32] ┆ u32 │
╞═════╪═══════════════════╪════════════════════╡
│ 0 ┆ [0, 811, … 1435] ┆ 152 │
│ 1 ┆ [1, 953, … 1723] ┆ 159 │
│ 2 ┆ [2, 355, … 835] ┆ 243 │
│ 3 ┆ [3, 102, … 1129] ┆ 110 │
│ 4 ┆ [4, 1280, … 1543] ┆ 226 │
└─────┴───────────────────┴────────────────────┘
Compatibility
Under some mild assumptions, (e.g. columns implement to_numpy()), PDS works with other eager dataframes. For example, with Pandas:
from polars_ds.compat import compat as pds2
df_pd["linear_regression_result"] = pds2.lin_reg(
df_pd["x1"], df_pd["x2"], df_pd["x3"],
target = df_pd["y"],
return_pred = True
)
df_pd
The magic here is the compat module and the fact that most eager dataframes implement the array protocal.
Other
Other common numerical functions such as: pds.convolve, pds.query_r2, pds.principal_components, etc. See our docs for more information.
Generally speaking, the more expressions you want to evaluate simultaneously, the faster Polars + PDS will be than Pandas + (SciPy / Sklearn / NumPy). The more CPU cores you have on your machine, the bigger the time difference will be in favor of Polars + PDS.
Road Map
All yours. Just let me know, and I will evaluate and get back to you!
Minimum Polars Support + Streaming Compatibility
The core package depends on Python Polars >=1.4.0, with the exclusions listed in
pyproject.toml. The source compatibility matrix pins Polars 1.44.2 and 2.0.0,
and runs the changed compatibility contracts on the minimum version, 1.4.0.
Python 3.9 uses Polars 1.x; Polars 2 requires Python >=3.10.
Compatibility regressions exercise lazy auto, streaming and in-memory execution,
including nulls, single-row batches, multiple chunks and grouped expressions.
Whole-column plugins may materialize their input inside a streaming query; this
does not make them bounded-memory algorithms. Fixed-seed random expressions use
the complete input or group so batch boundaries do not restart the sequence.
Polars large-index builds are not supported.
The Pipeline explode transform retains empty-list and null input rows by default
on both versions, including previously serialized pipelines. Statistical binning
preserves the linear
quantiles and interval labels of Polars 1 via the still-available qcut API;
bin_quantiles uses different breakpoints and is not a numerical replacement.
Build From Source
The guide here is not specific to LTS CPU, and can be used generally.
The best advice for LTS CPU is that you should compile the package yourself. First clone the repo and make sure Rust is installed on the system. Create a python virtual environment and install maturin in it. Next set the RUSTFLAG environment variable. The official polars-lts-cpu features are the following:
Since this project is mostly maintained by a single person, and a single person cannot be fluent with all topics in scientific programming, some of the code in this package is guided by AI and reviewed by me. I will not accept vibe-coded functions. For AI-generated PRs, see contributing.md. Once again, please understand that I have limited attention and if you submit an AI PR with thousands of lines of code, I may not keep up and decide not to include a large portion of the code due to maintenance reasons.
Works well with
Use together with polars-ds: extensions, drivers, servers and companion tools.
scipyPythie’s Index: 86Fundamental algorithms for scientific computing in Python423.2M downloads/mo
polarsPythie’s Index: 90Blazingly fast DataFrame library73.3M downloads/mo