BUG: SeriesGroupBy.value_counts is inconsistent with Series.value_counts when the Series is categorical · Issue #38672 · pandas-dev/pandas (original) (raw)


Note: Please read this guide detailing how to provide the necessary information for us to reproduce your bug.

Code Sample, a copy-pastable example

import pandas as pd

df = pd.DataFrame() df["col1"] = ["A", "A", "B", "B"] df["col2"] = pd.Categorical(["1", "2", "1", "1"], categories=["1", "2", "3"])

print(df.groupby("col1").col2.value_counts())

Problem description

A value_counts applied to the col2 Series:

yields:

1      3
2      1
3      0
Name: col2, dtype: int64

Because col2 is categorical we get the 0 count for value 3, as desired.

If we groupby col1 first

df.groupby("col1").col2.value_counts()

we get the following output:

col1  col2
A     1       1
      2       1
B     1       2
Name: col2, dtype: int64

Expected Output

The expected output can be achieved with a workaround:

df.groupby("col1").col2.apply(pd.Series.value_counts)

which yields:

col1   
A     2    1
      1    1
      3    0
B     1    2
      3    0
      2    0
Name: col2, dtype: int64

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 67a3d42
python : 3.7.5.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 158 Stepping 10, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None

pandas : 1.1.4
numpy : 1.19.1
pytz : 2019.3
dateutil : 2.8.0
pip : 20.2.3
setuptools : 41.2.0
Cython : 0.29.21
pytest : 5.3.5
hypothesis : None
sphinx : 2.4.1
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.4.1
html5lib : 1.0.1
pymysql : 0.9.3
psycopg2 : None
jinja2 : 2.10.3
IPython : 7.8.0
pandas_datareader: None
bs4 : 4.8.2
bottleneck : None
fsspec : 0.6.0
fastparquet : None
gcsfs : None
matplotlib : 3.1.3
numexpr : None
odfpy : None
openpyxl : 3.0.0
pandas_gbq : None
pyarrow : 1.0.1
pytables : None
pyxlsb : None
s3fs : None
scipy : 1.4.1
sqlalchemy : 1.3.10
tables : None
tabulate : 0.8.6
xarray : None
xlrd : 1.2.0
xlwt : None
numba : None