Skip to content

BUG: Fix construction of Categorical from pd.NA #31939

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 24 commits into from
Feb 23, 2020
Merged

BUG: Fix construction of Categorical from pd.NA #31939

merged 24 commits into from
Feb 23, 2020

Conversation

dsaxton
Copy link
Member

@dsaxton dsaxton commented Feb 12, 2020

Copy link
Member

@WillAyd WillAyd left a comment

Choose a reason for hiding this comment

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

lgtm

@WillAyd WillAyd added Categorical Categorical Data Type MultiIndex NA - MaskedArrays Related to pd.NA and nullable extension arrays labels Feb 13, 2020
@simonjayhawkins simonjayhawkins modified the milestones: 1.1, 1.0.2 Feb 15, 2020
@@ -458,6 +458,14 @@ def test_constructor_with_categorical_categories(self):
result = Categorical(["a", "b"], categories=CategoricalIndex(["a", "b", "c"]))
tm.assert_categorical_equal(result, expected)

def test_construction_with_null(self, nulls_fixture):
# https://github.com/pandas-dev/pandas/issues/31927
values = ["a", nulls_fixture]
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 add another value after nulls_fixture here to show that we are actually getting the correct codes

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure I understand this request. I did just realize though that pd.NA is not even part of nulls_fixture so will need to change this somehow.

Copy link
Contributor

Choose a reason for hiding this comment

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

it is, rebase on master

Copy link
Contributor

Choose a reason for hiding this comment

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

values = ['a', nulls_fixture, 'b']

Copy link
Member Author

Choose a reason for hiding this comment

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

Am I looking at the wrong fixture? I wasn't seeing pd.NA here: https://github.com/pandas-dev/pandas/blob/master/pandas/conftest.py#L444

Copy link
Member

Choose a reason for hiding this comment

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

Will be added in #31799

def test_multiindex_from_product_contains_na(self):
# https://github.com/pandas-dev/pandas/issues/31883
values1 = [np.array([0.0, pd.NA], dtype="object"), ["a", "b"]]
values2 = [np.array([0.0, np.nan], dtype="object"), ["a", "b"]]
Copy link
Contributor

Choose a reason for hiding this comment

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

wait, pd.NA is actually converted to np.nan here?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, probably not ideal (but better than an error). If merged would a follow-up issue to make sure pd.NA is used make sense? Or I could mark that the referenced issue is not actually closed and comment there.

Copy link
Contributor

Choose a reason for hiding this comment

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

no, pls do it here

Copy link
Contributor

Choose a reason for hiding this comment

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

followups are ok, but for relatively small things just fixing it in the same PR is better

Copy link
Member Author

Choose a reason for hiding this comment

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

I'd have to look more closely, but I'm not sure if having it return pd.NA instead of np.nan is an easy fix; this is already how it behaves for list input (which seems to be the documented behavior):

In [1]: import pandas as pd 
   ...:  
   ...: values = ["a", pd.NA] 
   ...:  
   ...: pd.Categorical(values) 
   ...:                                                                                                                            
Out[1]: 
[a, NaN]
Categories (1, object): [a]

In [2]: pd.__version__                                                                                                             
Out[2]: '1.0.1'

I think having it so that we at least get the same output and not an error for a numpy array with object dtype is still an improvement though? What are your thoughts @WillAyd ?

Copy link
Member

Choose a reason for hiding this comment

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

Agree it would be nice to maintain pd.NA - do you know the extra effort involved to do so?

Copy link
Member Author

@dsaxton dsaxton Feb 16, 2020

Choose a reason for hiding this comment

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

I'm not sure, I'd need to investigate a bit more. The logic doesn't seem too obvious though; should pd.NA be the default for missing values, or only when it's explicitly encountered? How should mixed missing value types get handled during construction (e.g., pd.Categorical(["a", np.nan, pd.NA]))? Personally I think having pd.NA as the default makes sense, but that seems like a large change.

Copy link
Member Author

Choose a reason for hiding this comment

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

Curious if @jorisvandenbossche has a preference? Always using pd.NA seems logical, probably just a question of "when" to implement that (as a lot of people are likely using Categorical and expecting to see NaN).

@jreback
Copy link
Contributor

jreback commented Feb 17, 2020

also pls run appropriate asvs this is a very performance sensitive path

@dsaxton
Copy link
Member Author

dsaxton commented Feb 17, 2020

also pls run appropriate asvs this is a very performance sensitive path

Not sure if others have encountered this, but I get a strange error trying to run the benchmark suite:

(pandas-dev) danielsaxton> asv continuous -f 1.1 upstream/master na-cat
Traceback (most recent call last):
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/bin/asv", line 5, in <module>
    from asv.main import main
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/__init__.py", line 32, in <module>
    from . import plugin_manager
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/plugin_manager.py", line 63, in <module>
    commands.__doc__ = commands._make_docstring()
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/commands/__init__.py", line 96, in _make_docstring
    parser, subparsers = make_argparser()
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/commands/__init__.py", line 84, in make_argparser
    subparser = commands[str(command)].setup_arguments(subparsers)
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/commands/machine.py", line 25, in setup_arguments
    defaults = machine.Machine.get_defaults()
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/machine.py", line 146, in get_defaults
    cpu = util.get_cpu_info()
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/util.py", line 996, in get_cpu_info
    sysctl = which('sysctl')
  File "/Users/danielsaxton/opt/miniconda3/envs/pandas-dev/lib/python3.7/site-packages/asv/util.py", line 361, in which
    raise IOError("Could not find '{0}' in {1}".format(filename, loc_info))
OSError: Could not find 'sysctl' in PATH

This reverts commit 14a737d.
tuples = [(0.0, "a"), (0.0, "b"), (np.nan, "a"), (np.nan, "b")]

result = pd.MultiIndex.from_product(values)
expected = pd.MultiIndex.from_tuples(tuples)
Copy link
Contributor

Choose a reason for hiding this comment

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

this is not correct, pd.NA should be preserved.

Copy link
Contributor

Choose a reason for hiding this comment

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

this might be a non-trivial patch and i would separate it from this PR.

Copy link
Contributor

Choose a reason for hiding this comment

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

remove this issue from the PR as this is not correct.

@jorisvandenbossche
Copy link
Member

BTW (short reaction, will look in more detail at the PR tomorrow), I don't we can preserve pd.NA in Categorical: because we can't yet have a Cateogorical with string dtype categories (you can't yet have an Index with nullable dtype).

That's also why I said in the issue that I was not sure it should actually work. Although I assume it is nice that it works and falls back to the normal object dtype backed categorical. But that means we will change behaviour when we can actually have a string dtype backed Categorical.

# https://github.com/pandas-dev/pandas/issues/31927
values = ["a", nulls_fixture, "b"]
result = Categorical(np.array(values, dtype=object))
expected = Categorical(values)
Copy link
Member

Choose a reason for hiding this comment

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

I am not sure this is a very good test. I mean: it is testing that lists vs object array are giving the same result (which is useful anyhow, as those should be consistent), but it is not testing how they are now constructed (eg it won't "preserve" pd.NA, and this is also not tested)

Copy link
Contributor

Choose a reason for hiding this comment

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

@dsaxton can you parameterize this on klass (np.array and list), then hard code the results in a categorical (meaning use _from_codes and an explict list of categories)

Co-Authored-By: Joris Van den Bossche <[email protected]>
tuples = [(0.0, "a"), (0.0, "b"), (np.nan, "a"), (np.nan, "b")]

result = pd.MultiIndex.from_product(values)
expected = pd.MultiIndex.from_tuples(tuples)
Copy link
Contributor

Choose a reason for hiding this comment

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

remove this issue from the PR as this is not correct.

@jorisvandenbossche
Copy link
Member

remove this issue from the PR as this is not correct.

Not sure why that test needed to be removed, as it still tests the behaviour that this PR is enabling.

See my comment above (#31939 (comment)) about that it is currently not possible to have pd.NA in Categoricals or MultiIndex. So either we are fine with the error you get now (and so this PR is not needed) or either we are fine with it being converted to np.nan (for now), but then we should also test that?

# https://github.com/pandas-dev/pandas/issues/31927
values = ["a", nulls_fixture, "b"]
result = Categorical(np.array(values, dtype=object))
expected = Categorical(values)
Copy link
Contributor

Choose a reason for hiding this comment

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

@dsaxton can you parameterize this on klass (np.array and list), then hard code the results in a categorical (meaning use _from_codes and an explict list of categories)

Copy link
Contributor

@jreback jreback left a comment

Choose a reason for hiding this comment

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

thanks @dsaxton, comment about a followup issue for the changes to use checknull.

@jreback jreback merged commit 41bc226 into pandas-dev:master Feb 23, 2020
@jreback
Copy link
Contributor

jreback commented Feb 23, 2020

@meeseeksdev backport to 1.0.x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Categorical Categorical Data Type MultiIndex NA - MaskedArrays Related to pd.NA and nullable extension arrays
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Construction of Categorical from array with pd.NA failing
5 participants