[Python] Unable to Check Dimensionality with Pint (DataFrame Elements)

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to check the dimensionality of quantities passed to a function using the pint package. Specifically, I have a Pandas DataFrame where column data types are set using pint_pandas. I want to pass elements of this DataFrame to my function.

    import pandas as pd
    import pint
    ureg = pint.UnitRegistry()
    import pint_pandas

    df = pd.DataFrame(
    {
    ('range', 'km'): [200]
    }
    ).pint.quantify(level=1)

    @ureg.check(
    '[length]',
    )
    def multiply_value(range):
    return range * 2

    multiply_value(df.iloc[0]['range'])


    Unfortunately, this returns an error:

    {
    "name": "DimensionalityError",
    "message": "Cannot convert from '200 kilometer' ([length]) to 'a quantity of' ([length])",
    "stack": "---------------------------------------------------------------------------
    DimensionalityError Traceback (most recent call last)
    Cell In[100], line 18
    12 @ureg.check(
    13 '[mass]',
    14 )
    15 def multiply_value(range):
    16 return range * 2
    ---> 18 multiply_value(df.iloc[0]['range'])

    File /opt/homebrew/Caskroom/miniconda/base/envs/aircraft_performance/lib/python3.13/site-packages/pint/registry_helpers.py:381, in check.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
    379 if not ureg.Quantity(value).check(dim):
    380 val_dim = ureg.get_dimensionality(value)
    --> 381 raise DimensionalityError(value, \"a quantity of\", val_dim, dim)
    382 return func(*args, **kwargs)

    DimensionalityError: Cannot convert from '200 kilometer' ([length]) to 'a quantity of' ([length])"
    }


    If I instead define a pint quantity myself, it works just fine:

    >>> range = 200 * ureg.km
    >>> multiply_value(range)
    400 kilometer

    Continue reading...

Compartilhe esta Página