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
import pandas as pd
x = pd.Series([1, None], dtype='Int32').to_frame(name='col')
# This is 'Int32Dtype()' as expected
print(pd.MultiIndex.from_frame(x).to_frame()['col'].dtype)
# This is float64
pd.MultiIndex.from_frame(x).factorize()[1].to_frame().iloc[:, 0].dtype
Issue Description
If you factorize an index, it should always be the case that the factorized index has the same dtypes as the original index, but this example shows that sometimes an extension dtype will be dropped and replaced with a more generic one.
(A related bug is that factorize of an Index should preserve column names.)
pd.factorize of a DataFrame with Int32 columns shows similar behaviour.
Expected Behavior
'Int32Dtype()' in both cases
Installed Versions
Comment From: jorisvandenbossche
@batterseapower thanks for the report!
That indeed seems to be a place where we don't have full support for extension dtypes. Looking at the implementation of the factorize method, I suppose this is because we don't have a custom implementation for MultiIndex, but use the base one that passes self._values to the factorize algorithm:
https://github.com/pandas-dev/pandas/blob/cc40732889b59d0ebd867b087691f02221e5666c/pandas/core/base.py#L1288-L1295
For a Series or simple Index, the _values will be the ExtensionArray. But for a MultiIndex, this _values gives you a 2d numpy array, and so that looses the extension dtype information.
But at least, as a stopgap, for MultiIndex input, it should cast the temporary uniques back to the original dtypes of the input MultiIndex.
Comment From: batterseapower
Interesting. I was concerned that a simple cast might lose info so I implemented a workaround like this:
def factorize(index: pd.Index, sort: bool = False):
    codes, uniques = index.factorize(sort=sort)
    # Work around issues discussed in https://github.com/pandas-dev/pandas/issues/62337
    assert isinstance(uniques, pd.Index)
    if uniques.nlevels == 1 and uniques.dtype == index.dtype:
        # Not preserved for some reason
        uniques.names = index.names
    else:
        example_indexes = np.full(len(uniques), -1, dtype=np.intp)
        example_indexes[codes] = np.arange(len(codes))
        assert (example_indexes >= 0).all()
        uniques = index[example_indexes]
    return codes, uniques
But it seems the correctness of factorize is dependent on _values not losing info anyway (e.g. due to casting ints to float types), so maybe post-casting the result is a fine approach.
Comment From: davidjcastrejon
take