Description
-
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']})
df.dtypes
gender object
education object
country object
dtype: object
df.groupby('country')['gender'].value_counts()
country gender
FR male 2
female 1
US female 2
male 1
Name: gender, dtype: int64
df.groupby('country')['gender'].value_counts().index.names
FrozenList(['country', 'gender'])
Now, if using a categorical type on the genre column, the column name is not saved in the index:
df['gender'] = df['gender'].astype('category')
df.dtypes
gender category
education object
country object
dtype: object
df.groupby('country')['gender'].value_counts()
country
FR male 2
female 1
US female 2
male 1
Name: gender, dtype: int64
df.groupby('country')['gender'].value_counts().index.names
FrozenList(['country', None])
Issue Description
The column name (here gender) is dropped when applying value_counts()
on a column of type category
.
It might be link with other problems in handling categorical types: #44001
This was working as of pandas v 1.2.3, and I could reproduce the bug starting with v 1.3.0, still present in v 1.3.4
Expected Behavior
Column name should be added in the index for uniformity with other types, as in the first example above with object type column.
Installed Versions
pandas : 1.3.4
numpy : 1.21.4
pytz : 2021.3
dateutil : 2.8.2
pip : 21.3.1
setuptools : 57.0.0
Cython : None
pytest : 6.2.4
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.6.3
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.1
IPython : 7.26.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.4.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.7.1
sqlalchemy : None
tables : None
tabulate : 0.8.9
xarray : 0.19.0
xlrd : None
xlwt : None
numba : None