Pandas version checks
-
[X] I have checked that this issue has not already been reported.
-
[X] 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
empty_ix = pd.MultiIndex.from_product([
pd.Index([], name='a', dtype=object),
pd.Index([], name='i', dtype='f4')
])
empty_ix.factorize() # Fails
# Names are lost
pd.MultiIndex.from_product([
pd.Index(['a', 'b'], name='a'),
pd.Index([0, 1, 0], name='i', dtype='f4')
]).factorize()[1].names
Issue Description
The first example should succeed, but actually it fails:
File ~/opt/conda/envs/mamba/envs/py3_2/lib/python3.11/site-packages/pandas/core/base.py:1203, in IndexOpsMixin.factorize(self, sort, use_na_sentinel)
1199 uniques = uniques.astype(np.float32)
1201 if isinstance(self, ABCIndex):
1202 # preserve e.g. MultiIndex
-> 1203 uniques = self._constructor(uniques)
1204 else:
1205 from pandas import Index
File ~/opt/conda/envs/mamba/envs/py3_2/lib/python3.11/site-packages/pandas/core/indexes/multi.py:222, in names_compat.<locals>.new_meth(self_or_cls, *args, **kwargs)
219 if "name" in kwargs:
220 kwargs["names"] = kwargs.pop("name")
--> 222 return meth(self_or_cls, *args, **kwargs)
File ~/opt/conda/envs/mamba/envs/py3_2/lib/python3.11/site-packages/pandas/core/indexes/multi.py:609, in MultiIndex.from_tuples(cls, tuples, sortorder, names)
607 if len(tuples) == 0:
608 if names is None:
--> 609 raise TypeError("Cannot infer number of levels from empty list")
610 # error: Argument 1 to "len" has incompatible type "Hashable";
611 # expected "Sized"
612 arrays = [[]] * len(names) # type: ignore[arg-type]
TypeError: Cannot infer number of levels from empty list
Probably because of the same underlying issue, MultiIndex.factorize
always loses the names
of the original index. It should preserve the original names instead.
Expected Behavior
First factorize()
should return (np.array([], dtype=np.intp), empty_ix)
Second example should return ['a', 'i']
instead of [None, None]
Installed Versions
Comment From: rhshadrach
Thanks for the report. Agreed this shouldn't raise, but I'm not certain about preserving names. pd.Index([2, 4, 3], name="a").factorize()
also does not preserve the name, and doing so might have some wide ranging complications (haven't checked). Further investigations welcome - in particular, if we do preserve names, what is the impact on the test suite?
Comment From: batterseapower
I also think names should be preserved in the regular Index case. It does break backwards compatibility to do this because existing code may be relying on them not being preserved, but leaving this aside it does seem very clear to me that dropping the names is surprising behaviour.
Comment From: rhshadrach
but leaving this aside it does seem very clear to me that dropping the names is surprising behaviour.
No disagreement here offhand, but this could have wide ranging implications and the impact needs to be investigated.