Skip to content

BUG: df.groupby().count() returns NaN instead of Zero #35028

Closed
@smithto1

Description

@smithto1
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

import pandas as pd

df = pd.DataFrame(
    {
        "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")),
        "cat_2": pd.Categorical(list("1111"), categories=list("12")),
        "value": [0.1, 0.1, 0.1, 0.1],
    }
)


# SeriesGroupBy on one pd.Categorical: unobserved categories have a count of 0
srg_grp = df.groupby(['cat_1'], observed=False)['value']
print(srg_grp.count())

# SeriesGroupBy on two pd.Categorical: unobserved categories have a count of 0
srs_grp = df.groupby(['cat_1', 'cat_2'], observed=False)['value']
print(srs_grp.count())

# DataFrameGroupBy on one pd.Categorical: unobserved categories have a count of 0
df_grp = df.groupby(['cat_1'], observed=False)
print(df_grp.count())

# DataFrameGroupBy on two pd.Categorical: unobserved categories have a count of NaN
df_grp = df.groupby(['cat_1', 'cat_2'], observed=False)
print(df_grp.count())

Problem description

When grouping by multiple pd.Categorical columns, DataFrameGroupBy.count() returns NaN for missing categories, and the dtype is float.

A similar problem is reported for .sum() in #31422

Expected Output

.count() should return zero for missing categories with a dtype of int.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 248c191
python : 3.8.3.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United Kingdom.1252

pandas : 1.1.0.dev0+1973.g248c19147.dirty
numpy : 1.18.5
pytz : 2020.1
dateutil : 2.8.1
pip : 20.1.1
setuptools : 47.3.1.post20200616
Cython : 0.29.20
pytest : 5.4.3
hypothesis : 5.18.0
sphinx : 3.1.1
blosc : None
feather : None
xlsxwriter : 1.2.9
lxml.etree : 4.5.1
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.15.0
pandas_datareader: None
bs4 : 4.9.1
bottleneck : 1.3.2
fsspec : 0.7.4
fastparquet : 0.4.0
gcsfs : 0.6.2
matplotlib : 3.2.1
numexpr : 2.7.1
odfpy : None
openpyxl : 3.0.3
pandas_gbq : None
pyarrow : 0.17.1
pytables : None
pyxlsb : None
s3fs : 0.4.2
scipy : 1.3.2
sqlalchemy : 1.3.17
tables : 3.6.1
tabulate : 0.8.7
xarray : 0.15.1
xlrd : 1.2.0
xlwt : 1.3.0
numba : 0.48.0

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions