|
31 | 31 | lib, |
32 | 32 | ) |
33 | 33 | from pandas._libs.hashtable import duplicated |
| 34 | +from pandas._libs.tslibs.timestamps import Timestamp |
34 | 35 | from pandas._typing import ( |
35 | 36 | AnyAll, |
36 | 37 | AnyArrayLike, |
@@ -3611,25 +3612,34 @@ def maybe_mi_droplevels(indexer, levels): |
3611 | 3612 |
|
3612 | 3613 | def _is_key_type_compatible(self, key, level): |
3613 | 3614 | """ |
3614 | | - Return True if the key type is compatible with the type of the level's values. |
| 3615 | + Return True if the key is compatible with the type of the level's values. |
3615 | 3616 | """ |
3616 | 3617 | if len(self.levels[level]) == 0: |
3617 | 3618 | return True # nothing to compare |
3618 | | - level_type = type(self.levels[level][0]) |
3619 | 3619 |
|
3620 | | - # Same type → OK |
3621 | | - if isinstance(key, level_type): |
| 3620 | + level_type = self.levels[level][0] |
| 3621 | + |
| 3622 | + # Allow slices (used in partial indexing) |
| 3623 | + if isinstance(key, slice): |
3622 | 3624 | return True |
3623 | | - # Allow Python int for numpy integer types |
3624 | | - if isinstance(level_type, np.integer) and isinstance(key, int): |
| 3625 | + |
| 3626 | + # datetime/date/Timestamp compatibility |
| 3627 | + datetime_types = (datetime.date, np.datetime64, Timestamp) |
| 3628 | + if isinstance(level_type, datetime_types) and isinstance( |
| 3629 | + key, datetime_types + (str,) |
| 3630 | + ): |
3625 | 3631 | return True |
3626 | 3632 |
|
3627 | | - # Allow Python float for numpy float types |
3628 | | - if isinstance(level_type, np.floating) and isinstance(key, float): |
| 3633 | + # numeric compatibility |
| 3634 | + if np.issubdtype(type(level_type), np.integer) and isinstance(key, int): |
| 3635 | + return True |
| 3636 | + if np.issubdtype(type(level_type), np.floating) and isinstance( |
| 3637 | + key, (int, float) |
| 3638 | + ): |
3629 | 3639 | return True |
3630 | 3640 |
|
3631 | | - # Allow subclasses of datetime.date for datetime levels |
3632 | | - if isinstance(level_type, datetime.date) and isinstance(key, datetime.date): |
| 3641 | + # string compatibility |
| 3642 | + if isinstance(level_type, str) and isinstance(key, str): |
3633 | 3643 | return True |
3634 | 3644 |
|
3635 | 3645 | return False |
|
0 commit comments