I just encountered a little bit of strange behavior for np.where with a Quantity.
The following example generates the output I would expect:
charges = np.array([1,0,0,1,-1])*unit.elementary_charge
np.where(charges == 0)[0]
where the output is an array with [1,2].
However, if we set the comparison to be anything other than 0, it just returns an empty array (not necessarily an error).
Two ways to make this work as expected, regardless of the value we are comparing against, we need to either compare the scalar value to the magnitude of the Quantity (i.e., the numpy array), or attach units to the scalar value we are comparing against.
# compare np.array to int/float/np.array by grabbing the magnitude
charges = np.array([1,0,0,1,-1])*unit.elementary_charge
np.where(charges.m == 1)[0]
# compare unit quantities by attaching units to the value we are comparing against
charge_to_compare = 1*unit.elementary_charge
np.where(charges == charge_to_compare)[0]
This also occurs for other comparison operations in numpy, such as np.all or np.any; when comparing a Quantity to 0, it provides the expected output, but any other value does not produce the expected output.
So the moral of the story is to be consistent when making comparisons (i.e., do not compare a Quantity to an integer/float/numpy array).
I'm mostly raising this issue so this is written down somewhere. This may be a known thing, but I didn't find it when looking in the issues on Pint.
I don't think there is anything specific that needs to be done, although it might be useful to have some notes in the documentation.
I just encountered a little bit of strange behavior for
np.wherewith aQuantity.The following example generates the output I would expect:
where the output is an array with [1,2].
However, if we set the comparison to be anything other than 0, it just returns an empty array (not necessarily an error).
Two ways to make this work as expected, regardless of the value we are comparing against, we need to either compare the scalar value to the magnitude of the
Quantity(i.e., thenumpyarray), or attach units to the scalar value we are comparing against.This also occurs for other comparison operations in numpy, such as
np.allornp.any; when comparing aQuantityto 0, it provides the expected output, but any other value does not produce the expected output.So the moral of the story is to be consistent when making comparisons (i.e., do not compare a
Quantityto an integer/float/numpy array).I'm mostly raising this issue so this is written down somewhere. This may be a known thing, but I didn't find it when looking in the issues on
Pint.I don't think there is anything specific that needs to be done, although it might be useful to have some notes in the documentation.