hgrecco / pint-pandas

Pandas support for pint
Other
172 stars 42 forks source link

feature request: add possibility to quantify with an external dict #50

Closed numenic closed 3 years ago

numenic commented 3 years ago

For now, one can use quantify() using a multi-level index by passing level value. It could be handy to quantify by means of an external dictionnary. For example:

df = pd.DataFrame({'a': 1, 2, 3], 'b': [4, 5, 6]})  # no specific dtypes, no multi-level
df = df.pint.quantify(by={"a": "cm", "b": "bar"})
andrewgsavage commented 3 years ago

You can use df.astype() to do almost this:

units_dict = {"a": "cm", "b": "bar"}
dtypes_dict = {col : "pint["+unit+"]" for col, unit in units_dict.items()}
dtypes_dict
{'a': 'pint[cm]', 'b': 'pint[bar]'}

df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
df = df.astype(dtypes_dict)
df.dtypes
a    pint[centimeter]
b           pint[bar]
dtype: object

That is a bit longwinded though compared to what you suggest though.

numenic commented 3 years ago

Sorry for the late answer. Good tip!