Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include thousand separator in numbers in polars output?

I'd like to generate a html output of a dataframe with thousand separators in the output.
However pl.Config does not seem to do anything:

import polars as pl

df = pl.DataFrame({'prod':['apple','banana','melon'], 'price':[7788, 1122, 4400]})
with pl.Config(
    thousands_separator=" "
):
    html = '<html><body><table><tr><th>Product</th><th>Price</th></tr>'
    html += ''.join(df.with_columns((pl.lit('<tr><td>')+
                                     pl.col('prod')+
                                     pl.lit('</td><td class="right">')+
                                     pl.col('price').cast(pl.String)+
                                     pl.lit('</td></tr>')
                                     ).alias('x')
                                    )
                      .get_column('x')
                      .to_list()
                    )
    html += '</table></body></html>'
    print(html)
like image 218
lmocsi Avatar asked Sep 07 '25 19:09

lmocsi


1 Answers

In addition to the answer provided, you are printing python strings, which Polars does not format for you regardless of type.

with pl.Config(thousands_separator=','):
    df = pl.select(int = pl.lit(1000), str = pl.lit('1000'))

    string = ''.join(df.get_column("str").to_list())
    print(f"{type(string) = }, {string = }")
    # type(string) = <class 'str'>, string = '1000'

    integer = df.get_column("int").item()
    print(f"{type(integer) = }, {integer = }")
    # type(integer) = <class 'int'>, integer = 1000

Here's a pure Python solution using f"{number:,}" to add a comma as a thousands separator then replacing it with a space. This may not be what you are after, but I figure I'd put it out there.

data = {"prod": ["apple", "banana", "melon"], "price": [7788, 1122, 4400]}

html_template = (
    "<html><body><table><tr><th>Product</th><th>Price</th></tr>{}</table></body></html>"
)
table_data = "".join(
    f'<tr><td>{prod}</td><td class="right">{price:,}</td></tr>'.replace(",", " ")
    for prod, price in zip(data["prod"], data["price"])
)

print(html_template.format(table_data))

Polars does have a format function, but it does not support Python format specifiers (e.g., f"{1000:,.2f}")

like image 116
Henry Harbeck Avatar answered Sep 11 '25 09:09

Henry Harbeck