Skip to content

BUG: loc treating 0/1 as boolean with boolean elements in the index column  #53267

@Rylie-W

Description

@Rylie-W

Pandas version checks

  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd
df = pd.DataFrame({'a': [True, False, "Missing"], "b": [1, 2, 3]}).set_index("a")
df.loc[0]
"""
Output: 
b    2
Name: False, dtype: int64
"""
df.loc[[0,1]]
"""
Output:
       b
a       
False  2
True   1
"""

df2 = pd.DataFrame({'a': [0, 1, True, False, "Missing"], "b": [1, 2, 3, 4, 5]}).set_index("a")
df2.loc[True]
"""
Output:
KeyError: 'True: boolean label can not be used without a boolean index'
"""

Issue Description

_LocIndexer._getitem_iterable() should distinguish boolean type from 0/1

Expected Behavior

KeyError: 0
KeyError: "None of [Index([0, 1], dtype='int64', name='a')] are in the [index]"

Installed Versions

INSTALLED VERSIONS

commit : 37ea63d
python : 3.9.6.final.0
python-bits : 64
OS : Darwin
OS-release : 21.6.0
Version : Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6000
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8
pandas : 2.0.1
numpy : 1.23.5
pytz : 2022.7.1
dateutil : 2.8.2
setuptools : 67.6.0
pip : 23.0.1
Cython : 0.29.33
pytest : 7.2.2
hypothesis : 6.69.0
sphinx : 5.3.0
blosc : 1.11.1
feather : None
xlsxwriter : 3.0.9
lxml.etree : 4.9.2
html5lib : 1.1
pymysql : 1.0.2
psycopg2 : 2.9.5
jinja2 : 3.1.2
IPython : 8.11.0
pandas_datareader: None
bs4 : 4.11.2
bottleneck : 1.3.7
brotli :
fastparquet : 2023.2.0
fsspec : 2023.3.0
gcsfs : 2023.3.0
matplotlib : 3.6.3
numba : 0.56.4
numexpr : 2.8.4
odfpy : None
openpyxl : 3.1.0
pandas_gbq : None
pyarrow : 11.0.0
pyreadstat : 1.2.1
pyxlsb : 1.0.10
s3fs : 2023.3.0
scipy : 1.10.1
snappy :
sqlalchemy : 2.0.6
tables : 3.8.0
tabulate : 0.9.0
xarray : 2023.2.0
xlrd : 2.0.1
zstandard : 0.20.0
tzdata : 2022.7
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIndexingRelated to indexing on series/frames, not to indexes themselvesgood first issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions