Description
-
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
V0_cat_idx = pd.CategoricalIndex([10, 20, 30],
categories=[10, 20, 30],
ordered=True,
name="V0")
V1_cat_idx = pd.CategoricalIndex(["B", "A"],
categories=["B", "A"],
ordered=True,
name="V1")
V2_cat_idx = pd.CategoricalIndex(["X", "Y"],
categories=["X", "Y"],
name="V2")
cat_midx = pd.MultiIndex.from_product([V0_cat_idx, V1_cat_idx, V2_cat_idx])
myseries = pd.Series(range(12), index=cat_midx)
norm = myseries.sum(level=["V1", "V2"])
myseries_norm = myseries.div(norm)
assert isinstance(myseries_norm.index.levels[0], pd.CategoricalIndex) # Failed
assert isinstance(myseries_norm.index.levels[1], pd.CategoricalIndex) # Failed
assert isinstance(myseries_norm.index.levels[2], pd.CategoricalIndex) # OK
Problem description
If we now look at the index type of myseries_norm
, we notice that we have lost the CategoricalIndex
type. However, the div operation is carried out on two Series with compatible multiindex consisting of CategoricalIndex
types.
The problem arises after div
operation but also with __mul__
.
Last info : if I change
cat_midx = pd.MultiIndex.from_product([V0_cat_idx, V1_cat_idx, V2_cat_idx])
by putting V0_cat_idx
level at the rightmost position :
cat_midx = pd.MultiIndex.from_product([V1_cat_idx, V2_cat_idx, V0_cat_idx])
The categorical indexes seem to be preserved...
Expected Output
assert isinstance(myseries_norm.index.levels[0], pd.CategoricalIndex) # OK
assert isinstance(myseries_norm.index.levels[1], pd.CategoricalIndex) # OK
assert isinstance(myseries_norm.index.levels[2], pd.CategoricalIndex) # OK
Output of pd.show_versions()
INSTALLED VERSIONS
commit : c7f7443
python : 3.8.10.final.0
python-bits : 64
OS : Linux
OS-release : 5.8.0-63-generic
Version : #71~20.04.1-Ubuntu SMP Thu Jul 15 17:46:08 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : fr_FR.UTF-8
LOCALE : fr_FR.UTF-8
pandas : 1.3.1
numpy : 1.19.2
pytz : 2020.1
dateutil : 2.8.1
pip : 20.2.2
setuptools : 49.6.0
Cython : None
pytest : 6.0.1
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : 2.8.6 (dt dec pq3 ext lo64)
jinja2 : 2.11.2
IPython : 7.18.1
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.5.2
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None