Skip to content

Fix .loc to handle ambiguity if a single Scalar is first element of a tuple #576

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

Closed
Dr-Irv opened this issue Mar 14, 2023 · 0 comments · Fixed by #581
Closed

Fix .loc to handle ambiguity if a single Scalar is first element of a tuple #576

Dr-Irv opened this issue Mar 14, 2023 · 0 comments · Fixed by #581

Comments

@Dr-Irv
Copy link
Collaborator

Dr-Irv commented Mar 14, 2023

From discussion in #575

In

IndexType | MaskType | list[HashableT] | Hashable,

Replace Hashable with slice | _IndexSliceTuple | Callable

If you make the suggested change, that will cause the test test_frame.py:test_loc_slice() to fail, but I now realize that the expression used there is ambiguous:

>>> df1 = pd.DataFrame(
...         {"x": [1, 2, 3, 4]},
...         index=pd.MultiIndex.from_product([[1, 2], ["a", "b"]], names=["num", "let"]),
...     )
>>> df1.loc[1, :]
     x
let
a    1
b    2
>>> df2 = pd.DataFrame({"x": [1,2,3,4]}, index=[10, 20, 30, 40])
>>> df2.loc[10, :]
x    1
Name: 10, dtype: int64

So the first argument as an integer could return a DataFrame or Series, dependent on whether the underlying index is a regular Index or MultiIndex

The solution is then to add another overload in _LocIndexerFrame.__getitem__():

    @overload
    def __getitem__(self, idx: tuple[ScalarT, slice]) -> Series | DataFrame: ...

Then modify the test in test_index_slice() to check that the type is Union[pd.Series, pd.DataFrame], and add another test corresponding to df2 above.

Originally posted by @Dr-Irv in #575 (comment)

@ramvikrams ramvikrams mentioned this issue Mar 16, 2023
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant