Skip to content

BUG: Avoid casting Int to object in Categorical.from_codes #31794

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Feb 12, 2020
Merged

BUG: Avoid casting Int to object in Categorical.from_codes #31794

merged 11 commits into from
Feb 12, 2020

Conversation

dsaxton
Copy link
Member

@dsaxton dsaxton commented Feb 7, 2020

@@ -644,7 +644,11 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
)
raise ValueError(msg)

codes = np.asarray(codes) # #21767
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm does this universally work if we just call to_numpy? I suppose could copy where undesired but maybe better than if...else branching

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah the if / else isn't too pretty but I think we have to worry if codes is a numpy array already or possibly a bare list. Ideally it'd be nice to just do pd.array(codes) instead of np.asarray(codes), but it looks like min and max haven't been implemented yet for IntegerArray so we get an error soon after.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In principle we could do a pd.array(codes).to_numpy("int64")
But a problem with that is that it will convert an already integer array of potentially lower bitsize than int64

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Has numpy a concept of "any integer dtype"?
Because then we could also simply do codes = np.asarray(codes, dtype="any int")

Another option could be this (to avoid converting an already int ndarray to int64)::

if not isinstance(codes, np.ndarray):
    codes = np.asarray(codes, dtype="int64")

which seems simpler as what you have now

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option could be this (to avoid converting an already int ndarray to int64)::

if not isinstance(codes, np.ndarray):
    codes = np.asarray(codes, dtype="int64")

which seems simpler as what you have now

I think we want it to raise if codes is something like [0.0, 1.0, 2.0] but this would make it a valid input

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we want it to raise if codes is something like [0.0, 1.0, 2.0] but this would make it a valid input

Ah, yes indeed...

(we should probably try to gather some of those situations we run into handling array-like input including nullable dtypes, to see if we can extract some useful helpers for those cases)

@WillAyd
Copy link
Member

WillAyd commented Feb 8, 2020

Can you merge master? CI failure should be resolved on master

@WillAyd WillAyd added the Categorical Categorical Data Type label Feb 8, 2020
@@ -644,7 +644,11 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
)
raise ValueError(msg)

codes = np.asarray(codes) # #21767
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In principle we could do a pd.array(codes).to_numpy("int64")
But a problem with that is that it will convert an already integer array of potentially lower bitsize than int64

codes = np.asarray(codes) # #21767
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
# Avoid the implicit conversion of Int to object
codes = codes.to_numpy(dtype=np.int64, na_value=np.nan)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codes shouldn't contain missing values (and the na_value=np.nan will not work anyway for a int64 dtype)

@@ -644,7 +644,11 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
)
raise ValueError(msg)

codes = np.asarray(codes) # #21767
if is_extension_array_dtype(codes) and is_integer_dtype(codes):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Has numpy a concept of "any integer dtype"?
Because then we could also simply do codes = np.asarray(codes, dtype="any int")

Another option could be this (to avoid converting an already int ndarray to int64)::

if not isinstance(codes, np.ndarray):
    codes = np.asarray(codes, dtype="int64")

which seems simpler as what you have now

# Avoid the implicit conversion of Int to object
codes = codes.to_numpy(dtype=np.int64)
else:
codes = np.asarray(codes) # #21767
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you don't need to add the issue number in code generally, unless you add a full expl (so here just remove i)

@@ -560,6 +560,15 @@ def test_from_codes_neither(self):
with pytest.raises(ValueError, match=msg):
Categorical.from_codes([0, 1])

def test_from_codes_with_nullable_int(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you also test with a NaN in the codes and Int64 (should raise)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The error message that ends up getting raised is maybe not the best: ValueError: cannot convert to '<class 'numpy.int64'>'-dtype NumPy array with missing values. Specify an appropriate 'na_value' for this dtype.. Would you recommend creating one specific to this method when we have NA values?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I think we should probably catch the error to raise a better one (because the error message now would be really confusing for users)

@jreback jreback added this to the 1.0.2 milestone Feb 9, 2020
@jreback jreback added the Regression Functionality that used to work in a prior pandas version label Feb 9, 2020
@jorisvandenbossche jorisvandenbossche removed the Regression Functionality that used to work in a prior pandas version label Feb 11, 2020
@jreback jreback added the Constructors Series/DataFrame/Index/pd.array Constructors label Feb 12, 2020
@jreback jreback merged commit 16684f2 into pandas-dev:master Feb 12, 2020
@jreback
Copy link
Contributor

jreback commented Feb 12, 2020

thanks @dsaxton

@jorisvandenbossche
Copy link
Member

@meeseeksdev backport to 1.0.x

@dsaxton dsaxton deleted the cat-from-int-codes branch February 12, 2020 15:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Categorical Categorical Data Type Constructors Series/DataFrame/Index/pd.array Constructors
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Categorical.from_codes fails for the (new nullable) Int64 dtype
4 participants