Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

API reference

Polars API reference

Polars fast multi-threaded DataFrames

Identifiers
102
With full guides
100
Types
3

Topics covered

  • DataFrame & LazyFrame
  • Expressions
  • Selecting & filtering
  • group_by
  • with_columns
  • Joins
  • Lazy evaluation
  • Streaming

Class

NameWhat it does
pl.DataFramepolars.DataFrame constructs an eager two-dimensional table from common columnar or row-oriented inputs. It can infer the schema or use an explicitly declared schema, with optional control over orientation and inference depth.
pl.LazyFramepolars.LazyFrame represents a deferred computation graph over tabular data. It enables whole-query optimization and parallel execution, and is Polars' preferred high-performance mode.
pl.Seriespolars.Series creates a one-dimensional, typed column from supported array-like data. You can provide its name and dtype, or let Polars infer the dtype from the values.
Exprpolars.Expr is Polars' composable expression type for describing column computations. Expressions support operators and methods and can be evaluated in DataFrame, LazyFrame, grouping, and window contexts.

Function

NameWhat it does
pl.read_csvReads CSV data eagerly into a Polars DataFrame. It supports paths, file-like inputs, bytes, and multiple sources, with options for delimiters, headers, schemas, column selection, and parsing behavior.
pl.scan_csvLazily scans one or more CSV inputs and returns a LazyFrame. Deferred execution lets Polars optimize filters and column selection before parsing data.
pl.colCreates a Polars expression representing one or more DataFrame columns. Use it inside contexts such as select and with_columns to reference, transform, or expand columns.
selectRuns Polars expressions without an existing DataFrame. It returns a DataFrame by default or a LazyFrame when eager=False.
filterFilters a DataFrame to rows whose predicate expressions evaluate to true. It preserves their order and supports keyword equality constraints that combine with other conditions.
group_byStarts a DataFrame grouping operation and returns a GroupBy object. Grouping keys may be columns or expressions, with optional preservation of group order.
with_columnsAdds expression-derived columns to a DataFrame while retaining existing columns. Columns with names already present are replaced, and the returned DataFrame reuses existing data rather than copying it.
joinDataFrame.join combines two DataFrames by matching key columns or expressions. Its default inner strategy keeps only matching rows; other strategies control which unmatched rows are retained.
collectExecutes a LazyFrame query and materializes its result as a DataFrame. It supports selectable execution engines, query optimization controls, and optional background execution.
pl.whenStarts a conditional expression built from chained when/then branches and an optional otherwise fallback. The first true condition determines the selected value.
aggCompute one or more aggregations for every group in a DataFrame group-by operation. Positional expressions and named keyword aggregations can be combined.
pl.read_parquetEagerly reads one or more Parquet sources into a Polars DataFrame. It supports column projection, row limits, parallel reading, Hive partitioning, cloud-storage options, and native or PyArrow backends.
pl.read_jsonReads a JSON file or readable input into a Polars DataFrame. Optional schema controls let you declare or override column types and limit inference scanning.
pl.read_ipcReads an Arrow IPC (Feather v2) file or byte stream into an eager Polars DataFrame, with optional column projection, row limiting, PyArrow selection, storage options, and row indexing.
pl.read_databaseExecutes a SQL query through a database connection and returns the results as a Polars DataFrame. Enable batch iteration to process large result sets incrementally.
pl.scan_parquetLazily scans one or more local or cloud-hosted Parquet files and returns a LazyFrame. Deferred execution lets Polars optimize filters and selected columns before reading data.
pl.from_pandasConverts a pandas DataFrame, Series, or Index into a Polars DataFrame or Series. Optional controls handle schema overrides, rechunking, NaN-to-null conversion, and index inclusion.
pl.from_arrowConverts an Arrow table or array into a Polars DataFrame or Series, usually without copying data. Optional schema, type overrides, and rechunking control the result.
pl.from_dictsConstructs a Polars DataFrame from an iterable of dictionaries, treating dictionary keys as column names. Types may be inferred or controlled with schema options, and strictness governs mismatched values.
pl.from_recordsConstructs a Polars DataFrame from a two-dimensional sequence of records. It supports explicit schemas, type overrides, orientation control, strict conversion, and bounded schema inference.
pl.litCreates a Polars expression representing a literal value. The value's data type is inferred by default, or controlled with dtype.
pl.sumpolars.sum creates an expression that sums all values in one or more named columns. It is shorthand for col(name).sum() and supports multiple names or a regular-expression selector.
pl.meanpolars.mean creates an expression that computes the mean of one or more named columns. It is shorthand for pl.col(columns).mean().
pl.minCreates an expression that computes the minimum value for one or more named columns. It is shorthand for col(names).min() and can be evaluated with operations such as select.
pl.maxCreates an expression that computes the maximum of each named column. It is shorthand for applying .max() to the selected columns.
pl.countpl.count creates expressions that count non-null values in one or more named columns. Its no-argument row-count form is deprecated; use pl.len() instead.
pl.firstReturns an expression that selects the first column when no names are supplied, or the first value from each named column when names are supplied.
pl.lastpl.last returns the last column when called without names, or the last value from each named column when names are supplied.
pl.structCollects columns or expressions into a single struct column. It returns an expression by default or an evaluated Series when eager=True.
pl.concatCombines multiple DataFrames, LazyFrames, or Series into one object. Choose row-wise, schema-union, horizontal, or key-alignment behavior with how.
pl.concat_strConcatenates multiple columns or expressions horizontally into one string column. It can insert a separator, casts non-string inputs to String, and optionally skips null values.
pl.formatCreates a Polars string expression by filling a template with literal values or expression results. It supports sequential, indexed, and column-name placeholders.
pl.allpl.all returns an expression selecting all columns when called without arguments, or processes supplied inputs. Horizontal bitwise-AND behavior is deprecated; use pl.all_horizontal for new code.
pl.anyReduces a Boolean column to whether it contains at least one True value. Nulls are ignored by default, or handled with Kleene logic when ignore_nulls=False.
pl.foldBuilds an expression that performs a left fold across multiple columns or expressions horizontally, applying a callback from an initial accumulator. It supports custom row-wise reductions and optional output-type control.
pl.elementReturns an expression representing the item currently processed by an eval or filter expression. Use it to transform, rank, or filter elements within Polars list expressions.
pl.arangepl.arange generates an integer range with an inclusive start and exclusive end. It returns an expression by default or an eagerly evaluated Series when eager=True.
pl.date_rangeGenerates a Date range between start and end using a full-day interval. It returns an expression by default or an eagerly evaluated Series when eager=True.
pl.int_rangeGenerates an integer range with an inclusive start and exclusive end. It returns an expression by default or an immediately evaluated Series when eager=True.

Module

NameWhat it does
df.selectSelects columns and evaluates Polars expressions to produce a new DataFrame. Inputs may be column names, iterables of names or expressions, and keyword expressions with explicit output names.
df.filterFilters a DataFrame's rows using boolean expressions or keyword equality constraints. Only rows whose conditions evaluate to true remain, in their original order; false and null results are discarded.
df.with_columnsAdds expression-derived or literal columns to a DataFrame while retaining existing columns. Existing names are replaced, and keyword expressions use their keywords as output names.
df.group_byStarts a group-by operation over columns or expressions and returns a GroupBy object for per-group aggregation. Group order can optionally follow input order with maintain_order=True.
df.aggComputes one or more expression-based aggregations for every group in a GroupBy object. Positional and keyword aggregations are supported, with keyword names becoming output column names.
df.sortSort a Polars dataframe by one or more columns or expressions. Control direction, null placement, threading, and ordering of equal rows.
df.joinDataFrame.join combines two DataFrames with SQL-like semantics. Choose shared keys with on or distinct key expressions with left_on and right_on, and select the join behavior with how.
df.pivotCreates a spreadsheet-style pivot table in eager mode, turning values from on into columns and retaining index keys as rows. Use aggregate_function when an index/on group can contain multiple values.
df.meltModule
df.unpivotReshapes a DataFrame from wide to long form, retaining optional identifier columns. Selected measured columns become rows represented by variable and value fields.
df.headReturns the first n rows of a Polars DataFrame. By default, it returns five rows; a negative n omits that many rows from the end.
df.tailReturns the last n rows of a DataFrame. The default is five rows; negative n returns all rows except the first abs(n) rows.
df.limitDataFrame.limit(n) returns the first n rows as a DataFrame, defaulting to five rows. A negative n returns all rows except the last abs(n) rows.
df.sliceSelect a row slice from a Polars DataFrame using a starting offset and optional length. Negative offsets are supported, and a missing length selects through the final row.
df.dropRemoves one or more columns from a Polars DataFrame and returns the resulting DataFrame. It accepts names, iterables of names, or column selectors, with strict schema validation enabled by default.
df.renameRename DataFrame columns with an explicit old-to-new mapping or a function that derives new names. By default, Polars validates that mapped source names exist.
df.uniqueRemoves duplicate rows from a DataFrame. You can define duplicates with selected columns or expressions, choose which duplicate to retain, and optionally preserve input order.
df.explodeExpands List or Array values in selected DataFrame columns into separate rows, producing long-format data. It accepts names, expressions, selectors, and additional positional columns, with options for empty and null containers.
df.partition_byGroups a DataFrame by one or more columns and returns each group as a separate DataFrame. Choose list output or dictionary output keyed by group-value tuples.
df.sampleSamples rows from a Polars DataFrame using either a requested count or fraction. Options control duplicate selection, output ordering, and reproducibility.
df.describeReturns summary statistics for a DataFrame. Percentile selection and percentile interpolation can be customized.
df.collectMaterializes a LazyFrame's deferred query plan into a DataFrame. You can select the execution engine, run in the background, and configure query optimizations.
df.lazyStarts a lazy query from an existing DataFrame and returns a LazyFrame. Operations remain deferred until Polars executes or inspects the plan.
df.to_pandasConverts a Polars DataFrame to pandas. Enable PyArrow-backed extension arrays to preserve nulls and potentially avoid copying data.
df.write_csvSerializes a DataFrame to CSV text or writes it to a path or writable file-like object. Options cover compression, headers, delimiters, formatting, quoting, and storage access.
df.write_parquetWrites a Polars DataFrame to Apache Parquet. It accepts a path or writable binary stream and supports compression, statistics, layout tuning, PyArrow options, metadata, and partitioned datasets.
df.fill_nullFills null values in a DataFrame with a supplied value or expression, or with a built-in strategy. It returns a DataFrame with the replacements applied.
df.drop_nullsRemoves rows containing nulls from a Polars DataFrame. By default every column is checked, but subset can restrict the check to named columns or a selector.
df.castConverts selected DataFrame columns, or every column, to specified data types. Use mappings or selectors for targeted casts and strict=False to turn invalid conversions into nulls.
df.with_row_indexAdds a sequential integer column as the first column of a DataFrame. The column name and starting offset are configurable.
.aliasRenames the output of a Polars expression. Use it to give derived or literal expressions explicit, non-conflicting column names.
.castExpr.cast converts an expression to a specified data type. Failed casts raise by default, or become null with strict=False; numeric overflow can be wrapped explicitly.
.overComputes an expression over partitions while retaining a row-oriented result. It supports partition keys, optional within-partition ordering, and selectable mapping strategies for multi-value results.
.cum_sumReturns an expression that computes a running sum for the named column values. It is shorthand for applying Expr.cum_sum to a column expression.
.rolling_meanComputes a fixed-size moving mean over an expression or Series. It supports optional elementwise weights, a minimum non-null threshold, and centered output labels.
.shiftShifts expression values by a chosen number of row positions. Positive offsets behave like SQL LAG, negative offsets like LEAD, and fill_value can replace boundary nulls.
.diffCalculates discrete differences between expression values and values shifted by a specified number of positions. It can preserve or drop null results.
.fill_nullExpr.fill_null replaces null values with a literal, expression, or supported strategy such as forward, backward, min, max, mean, zero, or one. A limit can bound consecutive replacements for forward and backward filling.
.is_nullReturns a boolean expression that identifies null values element by element. It can be applied to individual expressions or selected columns in DataFrame transformations.
.is_inChecks whether each value in a Series occurs in another Series or collection. It returns a Boolean Series, with optional control over whether null is treated as a distinct value.
.map_elementsApplies a custom Python function to each element of a Polars expression. It is flexible but slower than native expressions, so use it only when native operations cannot express the logic.
.map_batchesMaps a custom function over multiple columns or expressions and returns one expression backed by a Series result. Specify the output type when possible, and use the scalar and elementwise flags to control result handling and optimization.
.rankAssign ranks to expression values while handling ties through configurable methods. It can rank ascending or descending and can be scoped to groups with over.
.qcutBins continuous expression values into discrete categories using quantiles. It supports explicit probabilities or a uniform bin count, optional labels, interval closure, duplicate handling, and breakpoint output; the stable documentation marks it deprecated since 2.0.0.
.cutBins continuous expression values into discrete categories using explicit breakpoints. It can return labeled categories or include each value’s bin endpoint.
.roundRounds floating-point expression values to a specified number of decimal places. The default half_to_even mode resolves ties by choosing the nearest even value.
.clipClips values outside optional lower and upper boundaries to those boundaries. It supports numeric and temporal expressions and can use literals or column-based bounds.
.str.containsChecks whether each string contains text matching a pattern. Patterns are regular expressions by default, with options for literal matching and invalid-pattern handling.
.str.replaceReplaces matching substrings in string expressions using a regular expression or literal pattern. By default, it changes only the first match.
.str.splitSplits string values in a Polars expression around a delimiter and produces a list of string fragments. The delimiter is literal by default, with options for retaining it or interpreting it as regex.
.dt.yearExtracts the calendar year from Date or Datetime values. The expression returns Int32 output and can be composed with other Polars expressions.
.dt.monthExtracts the calendar month from Date or Datetime expressions as one-based Int8 values from 1 through 12.
.dt.weekdayExtracts the ISO weekday number from Date or Datetime expressions. Monday is 1 and Sunday is 7, and the result has Int8 data type.
.list.lenCounts the number of elements in every list represented by an expression. Null elements are included, and the result is a UInt32 expression.
.list.evalApplies a Polars expression to every element of each list and returns the results as lists. Use pl.element() to reference the current element; optional inner parallelism is available but should not be enabled indiscriminately.
.collectExecutes a LazyFrame query and materializes its result as a DataFrame. It supports configurable engines, optimization controls, streaming execution, and optional background execution.
.explainReturns a string representation of a LazyFrame's query plan. It can show plain or tree output and expose optimized planning, engine selection, and optimization settings.
.profileModule
.sink_parquetEvaluates a LazyFrame query in streaming mode and writes its result to Parquet. It supports local paths, byte streams, partitioned destinations, compression, statistics, row groups, and storage options.

Search across every package and filter by type in your dashboard.

Start learning