hgrecco / pint-pandas

Pandas support for pint
Other
166 stars 40 forks source link

Setting output format temporarily #212

Open kenahoo opened 7 months ago

kenahoo commented 7 months ago

If I want to set the units output format just for writing one output file, is there something less global than setting the pint.UnitRegistry.default_format like below?

        prev_format = pint.UnitRegistry.default_format
        try:
            pint.UnitRegistry.default_format = '~C'
            df = df.pint.dequantify()
            df.to_csv(file, index=False)
        finally:
            pint.UnitRegistry.default_format = prev_format

In this case, the code is handed a unit-aware DataFrame and needs to write it out, but it doesn't have direct access to the UnitRegistry associated with it. It would be great if there's some property of df that controlled the formatting, or perhaps an argument to to_csv().

andrewgsavage commented 7 months ago

not at present. I think

with pint.UnitRegistry.option_context('default_format', '~C'):
    ...

would be a nice way of going about this. Would need some changes in pint

another approach would be a format arguement in dequantify+quantify.