Description
Pandas version checks
-
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 main branch of pandas.
Reproducible Example
import pandas as pd
data = [
["C","A","A","A"],
["C","A","B","A"],
["B","A","A","A"],
["B","A","A","B"],
]
data = pd.DataFrame(data, columns=["0","1","2","3"])
l_map = {
"C":"B", # When renaming the categories, the new categories 'alphabetical ordering'
"B":"C", # must be flipped compared to the old categories.
}
data["0"] = data["0"].astype("category")
data["0"] = data["0"].cat.rename_categories(l_map)
# We need a multiindex of atleast 4 levels deep
a = data.groupby(by=["0","1","2"])["3"].value_counts()
b = data.groupby(by=["0","1","2"])["3"].size()
# Sorting the multi-index prevents the unexpected behavior
# b = b.sort_index(ascending=False)
# Unexpected behavior; also for a.mul(b), a.add(b), a.sub(b)
c = a.div(b)
print(c.loc[pd.IndexSlice["B",:,:,:]])
# 1 2 3
# A A A NaN
# B A NaN
# A NaN NaN
# B NaN NaN
# Name: 3, dtype: float64
# Expected behavior
d = a.loc[pd.IndexSlice["B",:,:,:]]
e = b.loc[pd.IndexSlice["B",:,:]]
f = d.div(e)
print(f)
# 1 2 3
# A A A 1.0
# B A 1.0
# Name: 3, dtype: float64
Issue Description
Performing a division/multiplication/addition/subtraction using two multiindexes leads to NaN's where that is not appropriate.
Expected Behavior
Performing a math operation produces the expected result (see also code snippet above).
Installed Versions
INSTALLED VERSIONS
commit : 2e218d1
python : 3.8.5.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19041
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : Swedish_Sweden.1252
pandas : 1.5.3
numpy : 1.23.5
pytz : 2022.7.1
dateutil : 2.8.2
setuptools : 47.1.0
pip : 22.3.1
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.2
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : None
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.3
numba : 0.56.4
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.10.0
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : 2022.7