BUG: Fix MultiIndex partial-key lookup when np.datetime64 indexes datetime.date level (GH#55969)#64343
Open
logiop wants to merge 5 commits intopandas-dev:mainfrom
Open
Conversation
…etime.date level (GH#55969) When a MultiIndex has an object-dtype level containing `datetime.date` values, using `np.datetime64` as a partial key (e.g. `df.loc[(np_date, "A")]`) would silently ignore all key levels after the first date level and return all rows matching that date. Root cause: `_partial_tup_index` checks `lab not in lev` to detect keys that are absent from the level and takes a fast short-circuit path that returns immediately. The hashtable-based `__contains__` does not coerce `np.datetime64` to `datetime.date`, so the check incorrectly evaluated to True and the remaining key components (e.g. "A") were never applied. Fix: before the `lab not in lev` guard in both `_partial_tup_index` and `_get_loc_single_level_index`, convert a bare `np.datetime64` key to its Python-scalar equivalent (`datetime.date` for midnight timestamps, `datetime.datetime` otherwise) when the target level is object-dtype. This allows the normal lookup path to be taken and keeps subsequent key levels in play. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
logiop
added a commit
to logiop/pandas
that referenced
this pull request
Feb 28, 2026
…#64343 - Fix numpy datetime64 to Python datetime conversion by adding .item() to ensure proper type coercion in _partial_tup_index and _get_loc_single_level_index (resolves typing validation failure) - Fix namespace inconsistency in test_indexing.py: use DataFrame instead of pd.DataFrame to match file conventions - Reorganize imports in test_indexing.py to put datetime import at module level (resolves inconsistent-namespace-usage pre-commit check) These changes resolve GitHub Actions typing check failures and pre-commit.ci validation errors for the MultiIndex datetime.date + np.datetime64 bugfix. Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
ad4a1f5 to
fadf5cb
Compare
- Move import datetime to module level (isort compliance) - Remove local import datetime from function - Use DataFrame instead of pd.DataFrame (namespace consistency) Resolves pre-commit.ci validation errors: - isort check - inconsistent-namespace-usage check Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Apply isort rules: - multi.py: move 'import datetime' after 'from collections.abc' - test_indexing.py: reorder imports (from collections before import datetime) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add # type: ignore[union-attr] to suppress pyright errors where we access datetime.datetime attributes (hour, minute, second, microsecond, date) on a union type datetime.datetime | datetime.date. The code logic guarantees these attributes exist at those points. Fixes the typing validation check in GitHub Actions. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…dex-np-datetime64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #55969.
When a
MultiIndexhas an object-dtype level whose values aredatetime.dateobjects, usingnp.datetime64as a partial key(e.g.
df.loc[(np.datetime64("2023-11-01"), "A")]) silently ignores allkey components after the date level and returns every row whose date matches —
regardless of what the remaining key levels say.
Root cause
MultiIndex._partial_tup_indexguards withlab not in levto detect keysabsent from a level and then takes a fast short-circuit path that returns
immediately (without processing the remaining key levels).
The hashtable-based
__contains__does not coercenp.datetime64→datetime.date, so the membership test always evaluated toTrue(key"absent") for
np.datetime64keys against object-dtype levels holdingdatetime.datevalues. The subsequent key components (e.g."A","B")were therefore never applied, producing wrong results.
The same problem exists in
_get_loc_single_level_index, which is calledwhen the key falls into the
follow_keyportion ofMultiIndex.get_loc.Fix
Before the
lab not in levguard in both_partial_tup_indexand_get_loc_single_level_index, attempt to convert a barenp.datetime64key to its Python-scalar equivalent when the target level is object-dtype:
datetime.datedatetime.datetimeOnly substitute the converted value when it is actually present in the level,
so genuine type-mismatch key errors are preserved.
Example
Test plan
test_loc_datetime_date_index_with_np_datetime64inpandas/tests/indexes/multi/test_indexing.pywhich exercises:df.loc[(np_date, second_level)]for two different second-level valuesdatetime.date-keyed equivalentMultiIndex.slice_locswithnp.datetime64partial tuple keys🤖 Generated with Claude Code