Skip to content

Inconsistent behaviour when apply() used on categorical with NaN values #22191

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1198,7 +1198,7 @@ def map(self, mapper):
categories=new_categories,
ordered=self.ordered)
except ValueError:
return np.take(new_categories, self._codes)
return take_1d(new_categories, self._codes)

__eq__ = _cat_compare_op('__eq__')
__ne__ = _cat_compare_op('__ne__')
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/series/test_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,15 @@ def test_apply_dict_depr(self):
with tm.assert_produces_warning(FutureWarning):
tsdf.A.agg({'foo': ['sum', 'mean']})

def test_apply_categorical_with_nan_values(self):
# GH 20714
s1 = pd.Series(['1-1', '1-1', np.NaN], dtype='category')
s1 = s1.apply(lambda x: x.split('-')[0])

s2 = pd.Series(['1', '1', np.NaN], dtype='category')
Copy link
Member

Choose a reason for hiding this comment

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

Can you use the result/expected variable naming convention for this test, e.g.

s = pd.Series(['1-1', '1-1', np.NaN], dtype='category')
result = s.apply(lambda x: x.split('-')[0])
expected = pd.Series(['1', '1', np.NaN], dtype='category')

Additionally, the second example in the issue is the one that needs to be tested: pd.Series(['1-1','1-2',np.NaN], dtype='category'). The example you're testing is already working, so it doesn't test if the bug was actually fixed. Perhaps you could parametrize over the values of the Series and test both since expected is the same in both cases, e.g.

@pytest.mark.parametrize('values', [
    ['1-1', '1-1', np.NaN],
    ['1-1', '1-2', np.NaN]])
def test_apply_categorical_with_nan_values(self, values):
    # GH 20714
    s = pd.Series(values, dtype='category')
    ...

Copy link
Author

Choose a reason for hiding this comment

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

Thanks for the indications @jschendel !

Anyway I found another problem, doing:

@pytest.mark.parametrize('values', [
    ['1-1', '1-1', np.NaN],
    ['1-1', '1-2', np.NaN]])
def test_apply_categorical_with_nan_values(self, values):
s = pd.Series(values, dtype='category')
result = s.apply(lambda x: x.split('-')[0])
expected = pd.Series(['1', '1', np.NaN], dtype='category')
tm.assert_series_equal(result, expected, check_dtype=False)

I get an error due to the different classes of result and expected:

AssertionError: Categorical Expected type <class 'pandas.core.arrays.categorical.Categorical'>, found <class 'numpy.ndarray'> instead

This situation was already commented on issue #20714 and remarked as out of scope for this PR.
Knowing that, this test should pass. I thought I could do .astype('category') on result, but maybe I'm just missing another assert function inside tm that will work for this. Any ideas?


tm.assert_series_equal(s1, s2, check_dtype=False)


class TestSeriesAggregate(TestData):

Expand Down