BUG: Inconsistent behaviour for DataFrame.value_counts and Series.value_counts on categoricals (original) (raw)

Reproducible Example

import pandas as pd

df = (pd.DataFrame({'gender' : ['male', 'female', 'male', 'female', 'male'], 'country': ['BR', 'BR', 'US', 'BR', 'US']}) .astype('category') ) df.value_counts() # drops all empty categories

gender country

female BR 2

male US 2

BR 1

dtype: int64

also compare

(df .query("country != 'BR'") .value_counts() ) # drops non-observed categories

gender country

male US 2

dtype: int64

(df .query("country != 'BR'") ['gender'] .value_counts() ) # shows 0 for non-observed catgories

male 2

female 0

Name: gender, dtype: int64

Issue Description

DataFrame.value_counts() drops any non observed categories while Series.value_counts() shows 0 for non-observed categories.

There was some discussion about the zeroes for Series.value_counts() in this issue #8559, based on that I checked behaviour in R which also keeps the zeros:

gender <- factor(c('male', 'female', 'male', 'female', 'male')) country <- factor( c( 'BR', 'BR', 'US', 'BR', 'US') ) df <- data.frame(gender=gender, country=country) table(df) #> country #> gender BR US #> female 2 0 #> male 1 2

Expected Behavior

The following work-around gives the expected behaviour:

df.groupby("gender").country.value_counts()

gender

female BR 2

US 0

male US 2

BR 1

Name: country, dtype: int64

This fails however for more than two categorical variables.

Installed Versions

Details

INSTALLED VERSIONS

commit : 73c6825
python : 3.9.7.final.0
python-bits : 64
OS : Darwin
OS-release : 19.6.0
Version : Darwin Kernel Version 19.6.0: Thu Sep 16 20:58:47 PDT 2021; root:xnu-6153.141.40.1~1/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8

pandas : 1.3.3
numpy : 1.21.2
pytz : 2021.1
dateutil : 2.8.2
pip : 21.2.4
setuptools : 58.0.4
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 7.27.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None