-
-
Notifications
You must be signed in to change notification settings - Fork 19.1k
Description
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": [1, 2, 3], "b": [1, 2, 3], "c": [2, 3, 4]})
df.loc[(1, 2), :] # rows 2 and 3
df.loc[(1, 2), ["a"]] # rows 2 and 3 column "a"
df.loc[(1, 2), "a"] # assertionerror
# similarly if one uses a tuple to pull out the columns
Issue Description
When a dataframe is loc
-indexed with a tuple in a the first (row) slot and a scalar key in the column slot, we get an assertionerror, which is inconsistent with the behaviour if passing a non-scalar in the column slot.
Expected Behavior
Tuples are usually used in loc/iloc
indexing to indicate grouping of indices (between rows/columns) and levels in a multiindex. iloc
-indexing raises an IndexError
if any sub-indexer is itself a tuple (which is reasonable).
How should loc
-indexing behave here? I think it is not as easy as the iloc
case because a tuple can legitimately be a key for a Index
(not a multiindex). How about, if the index is not a multiindex, then a tuple is treated as a scalar key, and any failing lookup raises KeyError
. Rather than a tuple being treated like any other sequence.
So, concretely, in the above example all three approaches show raise an indexing error, since the label (1, 2)
is not in the row index.
In any case, the scalar-ness (or not) of the column key should not influence the eventual outcome in terms of whether an entry is found.
Installed Versions
INSTALLED VERSIONS
commit : 37ea63d
python : 3.11.3.final.0
python-bits : 64
OS : Linux
OS-release : 5.19.0-43-generic
Version : #44~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Mon May 22 13:39:36 UTC 2
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_GB.UTF-8
LOCALE : en_GB.UTF-8
pandas : 2.0.1
numpy : 1.24.3
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.7.2
pip : 23.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : None
IPython : 8.13.2
pandas_datareader: None
bs4 : None
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2023.3
qtpy : None
pyqt5 : None