__iter__ makes Quantity look list_like when it's not #1617
Replies: 4 comments 1 reply
-
I don't think that is the right way in Python. According to the docs link
Which is what Pint is doing. |
Beta Was this translation helpful? Give feedback.
-
So maybe this code from Pandas needs to be fixed?
Here's a reproducer of the problem, treating Pandas as just a nice way to organize random data (such as Quantities) into DataFrames that can otherwise be a nice way to slice and dice:
Here's the Pint-Pandas way of doing it:
Maybe the answer is YOU CANNOT USE PINT IN PANDAS UNLESS YOU USE PINT-PANDAS CORRECTLY. But it would be so nice to use the object nature of Quantities for Ad Hoc data that could be sliced and diced into PintArrays when we wanted to do math. Again, the Pandas people might say "all Pandas operations are math, including split/transform/combine". Seems like a harsh set of rules to adhere to, especially if they won't test iter-ability according to the rules. |
Beta Was this translation helpful? Give feedback.
-
I'm looking at how Pandas got to where it got to, and I think they are arguably in the wrong place for two reasons. The commit (lines 945-947 replaced with 934-941): pandas-dev/pandas@63ae9aa#diff-55001624a0932c1b6cee2e6ddb65dea85c1faf0dee84812c0ca0c32916a71438 Reason 1 is what we are talking about. Reason 2 is that
But the code they committed specifically overrides the override! So I cannot test my cool theory without opening that can of worms. |
Beta Was this translation helpful? Give feedback.
-
pandas will recognise Quantity scalars as scalars if they have ndim = 0. #1599 adds the ndim attribute to Quantity, returning 0 for scalars. This is enough to get is_list_like working. |
Beta Was this translation helpful? Give feedback.
-
The code defining a PlainQuantity includes the following:
When self.magnitude is not iterable, TypeError will be raised as per the comment, but that may be too later for the loosely defined
is_list_like
, which will report True if it so much finds an iter attribute (even an iter attribute that wants to raise a TypeError the instant anybody tries to use it).What if we hooked getattr so that if it's called with iter it will return
False
ifself.magnitude
is not iterable? Would that not both simplify the implementation as well as protectingis_list_like
from getting the wrong idea how this particular Quantity identifies?Beta Was this translation helpful? Give feedback.
All reactions