hgrecco / pint-pandas

Pandas support for pint
Other
166 stars 41 forks source link

convert element unit to column level #156

Closed mmarras closed 1 year ago

mmarras commented 1 year ago

I've been using pint for a while and as an effect, I get lots of calculation results of type pint.Quantity.

Working with pint-pandas works nicely, with having quantities on column level. However, how would I convert element level quantities to a column level quanitity?

Imagine I have a dictionary which is the result of a calculation:

myresults = {'time': 4.5497294e+10 <Unit('second')>,
 'key1': 8.18951293e+10 <Unit('second / hour')>,
 'key2': 2.1979329129201998e-10 <Unit('hour / second')>,
 'key3': 0.0028818395805818267 <Unit('dimensionless')>,
 'key4': 2.8548328990545646e-19 <Unit('dimensionless')>,
 'key5': 0.0028818395805818267 <Unit('dimensionless')>,
 'key6': 3.2577974783578724e-04 <Unit('1 / second')>}

if I cast this into a Dataframe via pd.Dataframe.from_dict(myresults) I get the units attached to the elements of the table. But not to the column. Now if I had the results for another set of input parameters and would add that to the df as a new row, then for me it would make sense to have a functionality that can convert to column-wide units (of course given that the units are convertable into each other). As a default it could use to_base_units if the units are not identical for each element of the column.

Does this exist? Does it make sense?

mmarras commented 1 year ago

I guess something like this would do:

_df = pandas.DataFrame.from_dict(mydict)
    for col in _df:
        try:
            unit = str(_df[col].values[0].u)
            _df[col] = _df[col].astype(f'pint[{unit}]')
        except AttributeError: # if it has no unit then dont recast
            pass

# to check
_df.pint.dequantify()
andrewgsavage commented 1 year ago

This PR would do what you want https://github.com/hgrecco/pint-pandas/pull/58

mmarras commented 1 year ago

Awesome, any timeline on when that becomes available? Is there a roadblock?