Skip to content

BUG: Respect Filtered Categorical in Crosstab #13073

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
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.18.2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
- Bug in ``SparseDataFrame`` in which ``axis=None`` did not default to ``axis=0`` (:issue:`13048`)
- ``pd.crosstab`` now respects filtered ``Categorical`` objects (:issue:`12298`)



Expand Down
11 changes: 9 additions & 2 deletions pandas/tools/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,15 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
crosstab : DataFrame
"""

index = com._maybe_make_list(index)
columns = com._maybe_make_list(columns)
def _make_list(arr):
# see gh-12298
if com.is_categorical(arr):
arr = Series(list(arr), name=arr.name)
Copy link
Contributor

Choose a reason for hiding this comment

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

There should be a more efficient way to do that (than convert to list in between), by using the dtype of the categories.


return com._maybe_make_list(arr)

index = _make_list(index)
columns = _make_list(columns)

rownames = _get_names(index, rownames, prefix='row')
colnames = _get_names(columns, colnames, prefix='col')
Expand Down
23 changes: 23 additions & 0 deletions pandas/tools/tests/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,29 @@ def test_crosstab_with_empties(self):
normalize=False)
tm.assert_frame_equal(nans, calculated)

def test_crosstab_filtered_categorical(self):
# see gh-12298
df = pd.DataFrame({'col0': list('abcabc'),
'col1': [1, 1, 2, 1, 2, 3],
'col2': [1, 1, 0, 1, 1, 0]})
data = [[2, 0], [1, 1]]
columns = pd.Index([1, 2], name='col1')
index = pd.Index(['a', 'b'], name='col0')
expected = pd.DataFrame(data, columns=columns, index=index)

# sanity check
filtered = df[df.col2 == 1]
result = pd.crosstab(filtered.col0, filtered.col1)
tm.assert_frame_equal(result, expected)

# casting columns to Categorical shouldn't change anything
for col in df.columns:
df[col] = df[col].astype('category')

filtered = df[df.col2 == 1]
result = pd.crosstab(filtered.col0, filtered.col1)
tm.assert_frame_equal(result, expected)

def test_crosstab_errors(self):
# Issue 12578

Expand Down