I have this code:
import polars as pl
df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]})
df.with_columns(pl.format('{:,.2f}', pl.col('size')))
But is fails:
ValueError - Traceback, line 3
2 df = pl.DataFrame({'size': [34.2399, 1232.22, -479.1]})
----> 3 df.with_columns(pl.format('{:,.2f}', pl.col('size')))
File polarsfunctionsas_datatype.py:718, in format(f_string, *args)
717 msg = "number of placeholders should equal the number of arguments"
--> 718 raise ValueError(msg)
ValueError: number of placeholders should equal the number of arguments
How can I format a float
or int
column using a format specifier like '{:,.2f}'
?
1
As outlined by @mozway, general format strings are not yet supported as part of pl.format
. The corresponding feature request already contains a nice polars implementation of (the most common) C-style sprint
formatting.
If efficiency is not too much of an issue (e.g. in exploratory data analysis), you can simply use pl.Expr.map_elements
and fall back to the naive python solution.
df.with_columns(
pl.col("size").map_elements(lambda x: f"{x:,.2f}", return_dtype=pl.String)
)
shape: (3, 1)
┌──────────┐
│ size │
│ --- │
│ str │
╞══════════╡
│ 34.24 │
│ 1,232.22 │
│ -479.10 │
└──────────┘
1
pl.format
is recognizing literal {}
, unlike python’s f-strings (if you run df.with_columns(pl.format('{:,.2f}'))
you’ll see that {:,.2f}
is left unchanged).
Thus you can’t use pl.format
the way you want (as posted as comment to the question, this is a feature request).
You might want to use one of the methods described here instead.
Code of pl.format
that shows how it works, it simply splits the strings on {}
(f_string.split("{}")
) and joins it back with the expressions in between:
def format(f_string: str, *args: Expr | str) -> Expr:
if f_string.count("{}") != len(args):
msg = "number of placeholders should equal the number of arguments"
raise ValueError(msg)
exprs = []
arguments = iter(args)
for i, s in enumerate(f_string.split("{}")):
if i > 0:
e = wrap_expr(parse_into_expression(next(arguments)))
exprs.append(e)
if len(s) > 0:
exprs.append(F.lit(s))
return concat_str(exprs, separator="")