Python Polars Cheatsheet (based on our O'Reilly book)

Aug 18, 2026 08:38 PM - 2 hours ago 3

Polars is simply a room for transforming, analyzing, and visualizing information pinch a fast and expressive DataFrame API. It was first released by Ritchie Vink successful 2020.

Install Polars pinch each of its optional limitations from the terminal:

uv pip instal "polars[all]"

Import Polars successful Python, and corroborate which versions of Polars and its dependencies you person installed:

import polars as pl pl.show_versions()

Polars queries typically publication data, toggle shape it, and constitute the consequence backmost out. A complete query is often a azygous concatenation of method calls:

fruit = pl.read_csv("fruit.csv") fruit.filter( (pl.col("weight") > 1000) & pl.col("is_round") ).write_parquet("fruit.parquet")

Throughout this cheatsheet, df is simply a DataFrame, lf is simply a LazyFrame, o is a second DataFrame to harvester pinch df, and e stands for immoderate expression. So e.abs() intends “call .abs() connected an expression”, arsenic successful pl.col("x").abs().

Data Structures#

Polars stores each of its information successful either a Series aliases a DataFrame.

Structure Description
Series One-dimensional. Holds a series of values of the aforesaid information type.
DataFrame Two-dimensional. Has rows and columns. One aliases much Series, each of the aforesaid length.
LazyFrame Resembles a DataFrame but holds nary data. A blueprint for generating a DataFrame.

Unlike pandas, Polars DataFrames do not person a statement index, and the API favors immutability and method chaining complete in-place modifications.

  • Create a Series by passing a sanction and a series of values:

    series = pl.Series("sales", [150.00, 300.00, 250.00])
  • Create a DataFrame from a dictionary of columns, wherever each worth is simply a Series or a plain Python sequence. You tin besides usage immoderate of the pl.read_*() functions to create 1 from a file:

    df = pl.DataFrame({ "sales": series, "id": [41, 42, 43] })
  • Because location is nary statement index, adhd 1 explicitly arsenic a file erstwhile you request it:

  • Turn a DataFrame into a LazyFrame. Alternatively, commencement from a LazyFrame straight pinch immoderate of the pl.scan_*() functions:

Eager and Lazy APIs#

The eager API executes immediately, whereas the lazy API builds an optimized query plan first. The optimizer automatically applies predicate pushdown (filtering arsenic early as possible) and projection pushdown (dropping columns that are ne'er used).

You move betwixt the 2 representations pinch .lazy() and .collect(): .lazy() turns a DataFrame into a LazyFrame, and .collect() executes a LazyFrame and gives you a DataFrame back.

  • Turn a DataFrame into a LazyFrame, and execute a LazyFrame to get a DataFrame:

    lf = df.lazy() df = lf.collect()
  • Use the streaming motor to process information out-of-core, truthful that datasets larger than representation tin still beryllium handled:

    lf.collect(engine="streaming")
  • Print the optimized query scheme arsenic text, aliases visualize it arsenic a graph, to spot what the optimizer decided to do:

    lf.explain() lf.show_graph()
  • Execute the query and return per-node timings, which tells you wherever the time actually goes:

Data Types#

Polars implements astir of the Apache Arrow representation specification, which is an efficient columnar format for level and hierarchical data.

Group Type Notes
Numeric Decimal 128 bits, precision, scale
Float32 Ranges ±3.4×10³⁸
Float64 Ranges ±1.8×10³⁰⁸
Int8 Ranges ±128
Int16 Ranges ±32,768
Int32 Ranges ±2.1×10⁹
Int64 Ranges ±9.2×10¹⁸
Int128 Ranges ±3.4×10³⁸
UInt8 Ranges 0–255
UInt16 Ranges 0–65,535
UInt32 Ranges 0–4.3×10⁹
UInt64 Ranges 0–1.8×10¹⁹
Temporal Date Days since Unix epoch
Datetime Microseconds since epoch
Duration Time long / delta
Time Time of day
Nested Array Fixed-length sequence
List Variable-length sequence
Struct Multiple fields pinch names
String String UTF-8 text, adaptable length
Categorical Dict of Strings
Enum Fixed dict of Strings
Other Boolean True / False
Binary Raw bytes
Null Represents Null / None

Inspecting Types#

  • Get a dictionary of file names and information types, aliases conscionable the database of information types:

  • Print 1 statement per column, including information types, which is useful for wide DataFrames wherever printing the DataFrame itself is unreadable:

  • Compute per-column summary statistics, including the number of nulls:

  • Report the in-memory size of the DataFrame successful the portion you inquire for:

Casting#

  • Cast a file to different information type. By default the formed is strict, truthful a worth that does not fresh raises an error:

    df.select(pl.col("id").cast(pl.UInt64))
  • Pass strict=False to formed without raising. Values that overflow the target type go nulls instead:

    df.select(pl.col("id").cast(pl.Int8, strict=False))

Reading and Writing Data#

Polars has 4 families of input and output functions, and which 1 you want depends connected whether you are moving eagerly aliases lazily:

  • read_*() sounds information into a DataFrame.
  • scan_*() creates a LazyFrame, deferring the existent reference until you collect.
  • write_*() writes a DataFrame to disk aliases to unreality storage.
  • sink_*() streams information to disk aliases to unreality retention without holding it each in memory.

Not each format supports each 4 operations:

Format read scan write sink
Avro
Clipboard
CSV
Database
Delta Lake
Excel / ODS
Iceberg
IPC / Feather
JSON
NDJSON
Parquet
PyArrow Dataset

Keyword arguments that galore of these functions judge include schema_overrides, n_rows, row_index_name, storage_options, and compression.

  • Scan files successful unreality retention by passing a URI pinch a glob pattern, and use storage_options to proviso credentials and region settings:

    pl.scan_parquet( "s3://bucket/*.parquet", storage_options={"aws_region": "us-east-2"} )
  • Stream a query consecutive to a walled Parquet dataset, penning 1 directory per chopped worth of the cardinal column:

    lf.sink_parquet(pl.PartitionBy("out/", key="x"))

Transforming Data#

Selecting Columns#

Keep columns based connected their name, information type, aliases position.

  • Select columns by name:

  • Select the consequence of an expression, truthful that you tin toggle shape columns connected their way out:

    df.select(pl.col("x") * 2)
  • Give the consequence of an look a sanction by utilizing a keyword argument, which produces a caller column:

    df.select(doubled=pl.col("x") * 2)
  • Select columns whose names lucifer a regular expression. The shape must commencement pinch ^ and extremity pinch $:

    df.select(pl.col("^.*_color$"))
  • Select each column:

Use file selectors for much flexibility. They tin beryllium mixed utilizing the group operators |, &, -, ^, and ~.

  • Import the selectors module, past prime columns by information type aliases by name pattern. See besides cs.string(), cs.contains(), and cs.first():

    import polars.selectors as cs df.select(cs.numeric()) df.select(cs.starts_with("val"))
  • Drop columns alternatively of keeping them. Pass strict=False truthful that names which do not beryllium are ignored alternatively than raising an error:

    df.drop("a", "y", strict=False)

Creating Columns#

New columns are added to the correct of the existing ones.

  • Add a caller file computed from an expression, naming it pinch a keyword argument:

    df.with_columns(new=pl.col("a") + 1)
  • Replace an existing file by producing an look pinch the aforesaid name. Here, nulls successful file a are replaced pinch zeros:

    df.with_columns(pl.col("a").fill_null(0))
  • Add a file pinch the aforesaid literal worth successful each row:

    df.with_columns(ones=pl.lit(1))
  • Add a file of statement indices. Use offset to commencement counting location different than zero:

    df.with_row_index(name="id", offset=1)

Filtering Rows#

Keep rows according to the values successful 1 aliases much columns aliases expressions.

  • Filter connected an existing boolean file by passing its name:

  • Filter pinch a azygous expression:

    df.filter(pl.col("x") > 5)
  • Pass aggregate expressions to harvester them pinch a logical AND. You tin besides constitute the AND explicitly pinch &, successful which lawsuit each comparison needs its ain parentheses:

    df.filter(pl.col("valid"), pl.col("x") > 5) df.filter(pl.col("valid") & (pl.col("x") > 5))
  • Use | for a logical OR:

    df.filter(pl.col("valid") | (pl.col("x") > 5))
  • Filter pinch keyword-argument constraints, which is shorthand for testing equality and combining the results pinch AND:

    df.filter(valid=True, x=5)
  • Keep only rows without immoderate missing values, aliases restrict the cheque to specific columns:

    df.drop_nulls() df.drop_nulls("x")
  • Remove copy rows. Use subset to determine which columns specify a duplicate, and support to choose which of the duplicates survives:

    df.unique(subset=["x"], keep="first")

Slicing and Sampling Rows#

Keep rows based connected their position.

  • Keep the first rows, aliases the past rows. Both default to five:

  • Keep a contiguous portion by giving an offset and a length. This keeps the 3rd statement done the seventh:

  • Keep each nth row:

  • Take a random sample of rows. Use with_replacement=True to let the aforesaid statement to beryllium drawn much than once, or fraction to sample a proportionality alternatively of a fixed number:

    df.sample(10) df.sample(10, with_replacement=True) df.sample(fraction=0.2)

Sorting Rows#

Reorder rows according to the values successful 1 aliases much columns aliases expressions.

  • Sort by a azygous column, ascending by default, aliases by aggregate columns in sequence:

    df.sort("x") df.sort("x", "y")
  • Move nulls to the extremity alternatively than the beginning:

    df.sort("x", nulls_last=True)
  • Reverse the order. When sorting by respective columns, walk a database of booleans to group the direction per column:

    df.sort("x", descending=True) df.sort("x", "y", descending=[False, True])
  • Sort by the consequence of an look alternatively than by a column, specified arsenic a computed ratio aliases the magnitude of a list:

    df.sort(pl.col("x") / pl.col("y")) df.sort(pl.col("l").list.len())
  • Keep only the k largest aliases smallest rows according to a column, which is cheaper than sorting everything and past slicing:

    df.top_k(5, by="score") df.bottom_k(5, by="score")

Reshaping#

Go from wide to agelong and backmost again.

  • Make a DataFrame longer by turning the values of 1 aliases much columns into rows, keeping scale columns arsenic identifiers:

    df.unpivot(on=["c"], index="id")
  • Make a DataFrame wider by turning the values of a file into caller columns. If the operation of connected and scale is not unique, proviso an aggregate_function to determine really to harvester the collisions:

    df.pivot(on="c", index="id", values="x") df.pivot(on="c", index="id", values="x", aggregate_function="sum")
  • Expand a database file truthful that each constituent gets its ain row, repeating the other columns:

  • Expand a struct file truthful that each section becomes its ain column:

  • Swap rows and columns. Use include_header=True to support the original file names arsenic a column:

    df.transpose(include_header=True)
  • Split a DataFrame into a database of smaller DataFrames, 1 per chopped worth of the fixed column:

Summarizing and Aggregating#

Split. Apply. Combine.

  • Split a DataFrame into groups by 1 aliases much columns. This gives you a GroupBy entity that you past aggregate:

    dfg = df.group_by("x") dfg = df.group_by("x", "y")
  • Apply a ready-made summary to each group. Count the rows per group, return the first rows of each group, aliases compute the mean of each file per group:

    dfg.len() dfg.head(2) dfg.mean()
  • Apply your ain usability to each group erstwhile nary built-in aggregation fits:

  • Use agg() for afloat power complete the aggregation. Passing an look without an aggregating method collects the values into a list, and naming the consequence pinch a keyword statement gives the caller file a sensible name:

    dfg.agg(...) dfg.agg(pl.col("y")) dfg.agg(avg=pl.col("y").mean())
  • Use a model look pinch over() to adhd an aggregation arsenic a caller file on the original DataFrame, without collapsing the rows:

    df.with_columns(avg=pl.col("y").mean().over("x"))
  • Group by a clip worth aliases an scale alternatively of by a category. group_by_dynamic() creates windows of a fixed duration, and group_by adds a regular grouping connected top:

    df.group_by_dynamic("timestamp", every="1h", group_by="store")
  • Use rolling() for a model that moves pinch each statement alternatively than successful fixed steps. This computes a seven-day rolling sum of income per store:

    df.rolling(index_column="date", period="7d", group_by="store").agg( pl.col("sales").sum() )
  • Create the rows that are missing from a regular clip series, truthful that every interval is represented:

    df.upsample( time_column="date", every="1d", group_by="store", maintain_order=True )
  • Aggregate crossed columns alternatively than down them. The horizontal functions harvester respective columns wrong each row:

    df.select(pl.sum_horizontal(cs.numeric())) df.select(pl.any_horizontal(cs.boolean()))

Joining and Concatenating#

Combine aggregate DataFrames into one.

  • Join 2 DataFrames connected a shared key. The default is an soul join, which keeps only the rows that lucifer connected both sides:

  • Use really to take a different subordinate strategy. A near subordinate keeps each statement of df:

    df.join(o, on="key", how="left")
  • When the cardinal has a different sanction successful each DataFrame, sanction some sides explicitly:

    df.join(o, left_on="a", right_on="b")
  • A afloat outer subordinate keeps each rows from some sides. Add coalesce=True to merge the 2 cardinal columns into one:

    df.join(o, on="key", how="full", coalesce=True)
  • Filtering joins return columns from df only, and usage o purely arsenic a filter. A semi subordinate keeps the rows of df that person a match, and an anti subordinate keeps the rows that do not:

    df.join(o, on="key", how="semi") df.join(o, on="key", how="anti")
  • A transverse subordinate produces the Cartesian merchandise of some DataFrames and therefore needs nary key:

  • Join connected the nearest lucifer alternatively than an nonstop one, which is the accustomed measurement to line up 2 clip series. Use by to lucifer precisely connected immoderate columns first:

    df.join_asof(o, on="ts", by="i")
  • Join connected an arbitrary predicate for inequality aliases different non-equi joins:

    df.join_where(o, pl.col("a") >= pl.col("b"))

Common keyword arguments for df.join() are left_on, right_on, coalesce, join_nulls, suffix, and validate, wherever validate accepts "m:m", "m:1", "1:m", and "1:1".

  • Stack DataFrames connected apical of each other, which requires matching columns:

  • Place DataFrames broadside by broadside instead, aliases return the national of their columns and fill successful the gaps pinch nulls:

    pl.concat([df, o], how="horizontal") pl.concat([df, o], how="diagonal")
  • Use a relaxed strategy to coerce mismatched information types alternatively of raising an error:

    pl.concat([df, o], how="vertical_relaxed")
  • Update the values successful df pinch the non-null values from different DataFrame, matching rows connected a key:

    df.update(o, on="id", how="left")

Expressions#

Definition of an expression

An look is simply a character of operations that picture really to conception 1 aliases more Series.

  • Series: Same-type array; file aliases standalone
  • Tree of operations: Single, linear, aliases branched
  • Describe: Passive recipe; needs usability to execute
  • Construct: Output whitethorn beryllium internal, not a caller column
  • One aliases more: One look tin make aggregate Series

Beginning Expressions#

Every look starts from a column, from each columns, aliases from a literal value.

  • Build an look based connected an existing column, connected each columns, aliases connected a literal value. Note that pl.col("*") and pl.all() are equivalent:

    pl.col("name") pl.col("*") pl.all() pl.lit("ok")
  • Generate a scope of integers, wherever the extremity worth is exclusive. This produces [0, 1, 2, 3, 4]:

  • Generate a scope of dates. The singular shape produces 1 range, while the plural shape produces a column of ranges, 1 per row. Integers, times, and datetimes person their ain *_range() and *_ranges() functions:

    pl.date_range(...) pl.date_ranges(...)

Combining Expressions pinch Arithmetic#

You tin execute arithmetic pinch some expressions and plain Python values. Every usability has an balanced method, which is useful erstwhile you for illustration to support a chain of method calls unbroken.

Operator Method Description
+ e.add(...) Addition
- e.sub(...) Subtraction
* e.mul(...) Multiplication
/ e.truediv(...) Division
// e.floordiv(...) Floor division
** e.pow(...) Power
% e.mod(...) Modulus
N/A e.dot(...) Dot product

Combining Expressions by Comparing#

Unlike successful Python, you cannot concatenation aggregate comparisons. Write (pl.col("x") > 0) & (pl.col("x") < 10) alternatively than 0 < pl.col("x") < 10.

Operator Method Description
< e.lt(...) Less than
<= e.le(...) Less than aliases adjacent to
== e.eq(...) Equal
>= e.ge(...) Greater than aliases adjacent to
> e.gt(...) Greater than
!= e.ne(...) Not equal

Combining Expressions pinch Boolean Logic#

Note that and, or, and not are reserved keywords successful Python, hence the underscores successful the method names.

Operator Method Description
& e.and_(...) Logical AND
| e.or_(...) Logical OR
~ e.not_() Logical NOT
^ e.xor(...) Logical XOR

Conditional Expression#

Chain when() and then() to build a conditional expression, and adjacent it with otherwise(). Conditions are evaluated successful bid and the first lucifer wins, truthful put the most specific information first:

df.with_columns( pl.when(pl.col("age") < 18).then(pl.lit("minor")) .when(pl.col("age") < 65).then(pl.lit("adult")) .otherwise(pl.lit("senior")) .alias("group") )

Math, Trigonometry, and Rounding#

  • e.abs(), e.sign(), e.exp(): absolute value, sign, and exponential.
  • e.cbrt(), e.sqrt(): cube guidelines and quadrate root.
  • e.log(...), e.log10(), e.log1p(): logarithms.
  • e.cos(), e.sin(), e.tan(): trigonometric functions.
  • e.cosh(), e.sinh(), e.tanh(): hyperbolic functions.
  • e.arccos(), e.arcsin(), e.arctan(): inverse trigonometric functions.
  • e.arccosh(), e.arcsinh(), e.arctanh(): inverse hyperbolic functions.
  • e.degrees(), e.radians(): person betwixt radians and degrees.
  • e.ceil(), e.floor(), e.round(...): rounding.
  • e.clip(...), e.cut(...), e.qcut(...): clip values to a range, aliases bin them into intervals of your choosing aliases into quantiles.

Missing Values and Shapes#

In Polars, null intends missing, whereas NaN is simply a float that results from undefined mathematics specified arsenic 0 / 0. The 2 are handled by abstracted methods.

  • e.fill_nan(...), e.fill_null(...): capable missing values.
  • e.is_finite(), e.is_infinite(): cheque for finite and infinite values.
  • e.is_nan(), e.is_not_nan(): cheque for NaN.
  • e.is_null(), e.is_not_null(): cheque for null.
  • e.drop_nans(), e.drop_nulls(): driblet missing values.
  • e.flatten(), e.reshape(...): reshape a database aliases column.
  • e.explode(), e.implode(): move a database into rows, aliases stitchery rows into a list.

Shifts, Cumulative, and Rolling#

  • e.backward_fill(...), e.forward_fill(...): capable nulls from the adjacent aliases the previous value.
  • e.interpolate(...), e.shift(...): interpolate betwixt known values, aliases move values up aliases down.
  • e.cum_count(...), e.cum_sum(...): cumulative count and sum.
  • e.cum_max(...), e.cum_min(...): cumulative maximum and minimum.
  • e.diff(...), e.pct_change(...): quality and percent alteration between rows.
  • e.ewm_mean(...), e.ewm_std(...), e.ewm_var(...): exponentially weighted moving statistics.
  • e.rolling_max(...), e.rolling_min(...): rolling maximum and minimum.
  • e.rolling_mean(...), e.rolling_median(...): rolling mean and median.
  • e.rolling_std(...), e.rolling_var(...): rolling modular deviation and variance.
  • e.rolling_map(...): use your ain usability complete a rolling window.

Sorting, Ranking, and Boolean#

  • e.sort(...), e.sort_by(...): benignant a file by its ain values, aliases by the values of different columns.
  • e.arg_sort(...): return the statement indices that would benignant the column.
  • e.shuffle(...), e.reverse(): shuffle values randomly, aliases reverse their order.
  • e.rank(...): delegate ranks to the data.
  • e.is_duplicated(), e.is_unique(): people which values are duplicated and which are unique.
  • e.is_first_distinct(), e.is_last_distinct(): people the first aliases the last occurrence of each chopped value.

Summaries and Statistics#

  • e.all(...), e.any(...): existent if each aliases immoderate of the values are true.
  • e.max(), e.min(), e.mean(): maximum, minimum, and mean.
  • e.nan_max(), e.nan_min(): maximum and minimum that propagate NaN.
  • e.median(), e.std(), e.var(...): median, modular deviation, and variance.
  • e.entropy(...), e.kurtosis(...), e.skew(...): distribution statistics.
  • e.product(), e.quantile(...), e.sum(): product, quantile, and sum.
  • e.arg_max(), e.arg_min(): scale of the maximum and minimum value.
  • e.first(), e.last(), e.get(...): get a worth by position.
  • e.mode(): the astir often occurring values.

Counting, Unique, and Selection#

  • e.len(): count each rows, including nulls.
  • e.count(): count only the non-null values.
  • e.null_count(): count the null values.
  • e.n_unique(), e.approx_n_unique(): number of unsocial values, precisely or approximately.
  • e.arg_unique(), e.unique(...): indices of the unsocial values, aliases the unique values themselves.
  • e.unique_counts(), e.value_counts(...): really often each unsocial worth occurs.
  • e.head(...), e.tail(...), e.limit(...): prime rows from the commencement aliases the end.
  • e.bottom_k(...), e.top_k(...): the k smallest aliases largest values.
  • e.gather(...), e.gather_every(...): return values by index, aliases return every nth value.
  • e.sample(...), e.slice(...): sample aliases portion wrong an expression.
  • e.arg_true(): the indices wherever the worth is true.
  • e.replace(...): switch values utilizing a dictionary.
  • e.search_sorted(...): find the insertion scale successful a sorted column.

Arrays and Lists#

Arrays person a fixed length; lists do not. Array methods unrecorded nether the arr namespace and database methods nether list.

  • Cast a file to an array of a fixed length, past usage the array namespace:

    e.cast(pl.Array(pl.Int8, 3)) e.arr.max() e.arr.sort()
  • Combine respective columns into a azygous database column:

  • Work pinch the contents of a database column: get the magnitude of each list, get an element by index, benignant the elements wrong each list, subordinate them into a single string, aliases trial whether a worth is present:

    e.list.len() e.list.get(0) e.list.sort() e.list.join("-") e.list.contains(5)

Categoricals and Enums#

Categoricals infer their categories from the information and benignant lexically, whereas Enums are fixed up beforehand and benignant successful declaration order.

  • Cast a String file to a Categorical, aliases to an Enum pinch an nonstop group of allowed values:

    e.cast(pl.Categorical) e.cast(pl.Enum(["Good", "Bad"]))
  • Retrieve the categories that a Categorical file ended up with:

Dates, Datetimes, Times, and Durations#

Dates way days, whereas Datetimes way microseconds. Methods for moving pinch them unrecorded nether the dt namespace.

  • Construct a Date, a Datetime, aliases a Duration from their components:

    pl.date(2026, 12, 31) pl.datetime(2026, 6, 30, 23, 59, 0) pl.duration(days=1)
  • Extract a azygous component, specified arsenic the month:

  • Replace individual clip units, leaving the remainder untouched:

  • Format a datetime arsenic a drawstring utilizing a format specification:

  • Convert a datetime to different clip zone:

    e.dt.convert_time_zone("UTC")
  • Express a long arsenic a number of seconds:

Strings#

Strings are UTF-8, truthful lengths and slices count characters, not bytes. String methods unrecorded nether the str namespace.

  • e.str.contains(...): cheque whether each worth matches a regular expression.
  • e.str.split(...): divided each worth by a separator into a list.
  • e.str.to_uppercase(): make each worth all-caps.
  • e.str.to_datetime(): parse each worth into a Datetime.
  • e.str.extract(r"(\d+)"): extract the first regular look seizure group.
  • e.str.strip_chars(...): trim whitespace, aliases different characters you specify, from both ends.

Structs#

A struct groups aggregate columns into a azygous statement element. Struct methods unrecorded nether the struct namespace.

  • Combine columns into a Struct, past extract a azygous section backmost out:

    pl.struct("a", "b") e.struct.field(...)
  • Rename the fields of a Struct, aliases adhd and set fields:

    e.struct.rename_fields(...) e.struct.with_fields(...)

Binaries#

Use the bin namespace for earthy byte information and for base64 and hexadecimal conversions.

  • Decode a base64 string, aliases encode bytes arsenic a hexadecimal string:

    e.bin.base64_decode() e.bin.hex_encode()

Output Names#

Control the last file names of your expressions pinch the sanction namespace.

  • Add a prefix to the existing name, aliases lowercase it:

    e.name.prefix(...) e.name.to_lowercase()

Meta#

Introspection methods, chiefly utilized erstwhile penning plugins, unrecorded nether the meta namespace.

  • e.meta.output_name(): get the sanction the look will output.
  • e.meta.is_regex(): cheque whether the look is simply a regular expression.
  • e.meta.has_multiple_outputs(): cheque whether the look produces multiple outputs.

Styling Data#

Use Great Tables to move a DataFrame into a presentation-ready table. Start from GT(df) and concatenation the methods that group up the stub and header, format the values, and adhd color:

from great_tables import GT ( GT(df) .tab_stub(rowname_col="...") .cols_label(...) .tab_header(title="...") .fmt_number(...) .fmt_nanoplot(...) .data_color(columns="...", palette="...") )
Great Tables example

Visualizing Data#

The built-in plotting methods usage Altair nether the hood, and are disposable from the plot namespace:

df.plot.scatter(x="...", y="...", color="...")
Altair scatter plot

Many different packages tin activity pinch Polars DataFrames directly, including Plotnine, Plotly, hvPlot, Seaborn, and Matplotlib. For thing that cannot, person to pandas first pinch df.to_pandas().

from plotnine import * ggplot(df, aes(x="", y="", color="")) + geom_point()
Plotnine constituent plot

Polars Cloud#

Execute a query connected a cluster of instances successful your ain environment. Describe the compute you want pinch a ComputeContext, past tally a LazyFrame remotely against it:

import polars_cloud as pc ctx = pc.ComputeContext( workspace="workspace_name", cpus=4, memory=16, cluster_size=32 ) lf.remote(ctx).execute().await_result()

Book#

 The Definitive Guide This cheatsheet is based connected the book Python Polars: The Definitive Guide by Jeroen Janssens and Thijs Nieuwdorp, published by O’Reilly. The book is disposable successful some people and ebook formats astatine your favourite bookstore. Visit polarsguide.com for details.

More