Skip to content

ENH: DataFrameGroupby.value_counts #43564

Closed
@corriebar

Description

@corriebar

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

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

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

Reproducible Example

import pandas as pd

df = pd.DataFrame({'gender': ['female', 'male', 'female', 'male', 'female', 'male'], 
                  'education': ['low', 'medium', 'high', 'low', 'high', 'low'],
                  'country': ['US', 'FR', 'US', 'FR', 'FR', 'US']})
# These all work fine:
# value_counts() on a DataFrame
df[['gender', 'education']].value_counts(normalize=True)
df['gender'].value_counts(normalize=True) # on a Series
df.groupby('country')['gender'].value_counts(normalize=True) # on a SeriesGroupby

# but fails on DataFrameGroupBy
df.groupby('country')[['gender', 'education']].value_counts(normalize=True)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/var/folders/xz/_nt7tl1s0jx2f5_8rwc8kc0r0000gp/T/ipykernel_96325/3153685003.py in <module>
----> 1 df.groupby('country')[['gender', 'education']].value_counts(normalize=True)

~/opt/anaconda3/envs/pandas_dev/lib/python3.9/site-packages/pandas/core/groupby/groupby.py in __getattr__(self, attr)
    909             return self[attr]
    910 
--> 911         raise AttributeError(
    912             f"'{type(self).__name__}' object has no attribute '{attr}'"
    913         )

AttributeError: 'DataFrameGroupBy' object has no attribute 'value_counts'

Issue Description

Since value_counts() is defined both for a Series and a DataFrame, I also expect it to work on both a SeriesGroupBy and a DataFrameGroupBy.

There are some related Issues: #39938 and #6540, these have been dismissed so far with the argument that size() already does that, but size() alone is not enough to get the proportions per group.

Expected Behavior

I managed to get the desired behaviour by applying value_counts() to each group:

def compute_proportions(df, var):
    return (df[var]
        .value_counts(normalize=True)
    )
(df.groupby('country')
  .apply(compute_proportions, var=['gender', 'education'])
)
country  gender  education
FR       female  high         0.333333
         male    low          0.333333
                 medium       0.333333
US       male    low          0.666667
         female  high         0.333333
dtype: float64

Installed Versions

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: Tue Jun 22 19:49:55 PDT 2021; root:xnu-6153.141.35~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

Metadata

Metadata

Assignees

Labels

AlgosNon-arithmetic algos: value_counts, factorize, sorting, isin, clip, shift, diffEnhancementGroupby

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions