Skip to content

Commit 6654c02

Browse files
[backport 2.3.x] BUG: preserve (object) dtype in factorize (#60118) (#60174)
BUG: preserve (object) dtype in factorize (#60118) * BUG: preserve (object) dtype in factorize * add fallback for float16 (cherry picked from commit 13926e5)
1 parent 826c230 commit 6654c02

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

pandas/core/base.py

+9-3
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
from pandas.core.dtypes.generic import (
4949
ABCDataFrame,
5050
ABCIndex,
51+
ABCMultiIndex,
5152
ABCSeries,
5253
)
5354
from pandas.core.dtypes.missing import (
@@ -1198,13 +1199,18 @@ def factorize(
11981199
if uniques.dtype == np.float16:
11991200
uniques = uniques.astype(np.float32)
12001201

1201-
if isinstance(self, ABCIndex):
1202-
# preserve e.g. MultiIndex
1202+
if isinstance(self, ABCMultiIndex):
1203+
# preserve MultiIndex
12031204
uniques = self._constructor(uniques)
12041205
else:
12051206
from pandas import Index
12061207

1207-
uniques = Index(uniques)
1208+
try:
1209+
uniques = Index(uniques, dtype=self.dtype)
1210+
except NotImplementedError:
1211+
# not all dtypes are supported in Index that are allowed for Series
1212+
# e.g. float16 or bytes
1213+
uniques = Index(uniques)
12081214
return codes, uniques
12091215

12101216
_shared_docs[

0 commit comments

Comments
 (0)