Skip to content

DOC: Clarify Categorical Crosstab Behaviour #13177

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
10 changes: 10 additions & 0 deletions doc/source/reshaping.rst
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,16 @@ If ``crosstab`` receives only two Series, it will provide a frequency table.

pd.crosstab(df.A, df.B)

Any input passed containing ``Categorical`` data will have **all** of its
categories included in the cross-tabulation, even if the actual data does
not contain any instances of a particular category.

.. ipython:: python

foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
pd.crosstab(foo, bar)

Normalization
~~~~~~~~~~~~~

Expand Down
16 changes: 15 additions & 1 deletion pandas/tools/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,11 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
Notes
-----
Any Series passed will have their name attributes used unless row or column
names for the cross-tabulation are specified
names for the cross-tabulation are specified.

Any input passed containing Categorical data will have **all** of its
categories included in the cross-tabulation, even if the actual data does
not contain any instances of a particular category.

In the event that there aren't overlapping indexes an empty DataFrame will
be returned.
Expand All @@ -434,6 +438,16 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
bar 1 2 1 0
foo 2 2 1 2

>>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
>>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
>>> crosstab(foo, bar) # 'c' and 'f' are not represented in the data,
# but they still will be counted in the output
col_0 d e f
row_0
a 1 0 0
b 0 1 0
c 0 0 0

Returns
-------
crosstab : DataFrame
Expand Down