Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[backport 2.3.x] BUG: preserve (object) dtype in factorize (#60118) #60174

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
@@ -48,6 +48,7 @@
from pandas.core.dtypes.generic import (
ABCDataFrame,
ABCIndex,
ABCMultiIndex,
ABCSeries,
)
from pandas.core.dtypes.missing import (
@@ -1198,13 +1199,18 @@ def factorize(
if uniques.dtype == np.float16:
uniques = uniques.astype(np.float32)

if isinstance(self, ABCIndex):
# preserve e.g. MultiIndex
if isinstance(self, ABCMultiIndex):
# preserve MultiIndex
uniques = self._constructor(uniques)
else:
from pandas import Index

uniques = Index(uniques)
try:
uniques = Index(uniques, dtype=self.dtype)
except NotImplementedError:
# not all dtypes are supported in Index that are allowed for Series
# e.g. float16 or bytes
uniques = Index(uniques)
return codes, uniques

_shared_docs[
Loading