Skip to content

np.isfinite() changes internal type? #481

@dopplershift

Description

@dopplershift

I have no idea what's going on here:

import numpy as np
from pint import UnitRegistry
ureg = UnitRegistry()
a = np.arange(2.)
au = a * ureg.m

# Numpy Arrays
print('Numpy (base):', [type(v) for v in a])
print('Numpy (isfinite):', [type(v) for v in a if np.isfinite(v)])

# Quantity
print('Pint (base):', [type(v.magnitude) for v in au]) # ok
print('Pint (isfinite):', [type(v.magnitude) for v in au if np.isfinite(v)]) # Huh?

Outputs:

Numpy (base): [<class 'numpy.float64'>, <class 'numpy.float64'>]
Numpy (isfinite): [<class 'numpy.float64'>, <class 'numpy.float64'>]
Pint (base): [<class 'numpy.float64'>, <class 'numpy.float64'>]
Pint (isfinite): [<class 'numpy.ndarray'>, <class 'numpy.ndarray'>]

Why on earth does calling a numpy function modify the Quantity in-place???

The reason this even matters is because this works:

print([format(v, '.0f') for v in au])
['0 meter', '1 meter']

while this:

print([format(v, '.0f') for v in au if np.isfinite(v)])

gives me a traceback (due to NumPy not implementing __format__):

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-64-929696747b8d> in <module>()
----> 1 [format(v, '.0f') for v in au if np.isfinite(v)]

<ipython-input-64-929696747b8d> in <listcomp>(.0)
----> 1 [format(v, '.0f') for v in au if np.isfinite(v)]

/Users/rmay/miniconda3/envs/py35/lib/python3.5/site-packages/pint/quantity.py in __format__(self, spec)
    139             obj = self
    140         return '{0} {1}'.format(
--> 141             format(obj.magnitude, remove_custom_flags(spec)),
    142             format(obj.units, spec)).replace('\n', '')
    143 

TypeError: non-empty format string passed to object.__format__

Metadata

Metadata

Assignees

No one assigned

    Labels

    numpyNumpy related bug/enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions