Skip to content

BUG: Using tuples to specify single columns in .loc #54464

@SudhanAnnamalai

Description

@SudhanAnnamalai

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
import numpy as np

df = pd.DataFrame(np.random.randn(5,4), 
                  index = ["a", "b", "c", "d", "e"],
                  columns = ["One", "Two", "Three", (6, "two")])

Issue Description

#Error line
df.loc[:, (6, "two")] #KeyError: "None of [Index([6, 'two'], dtype='object')] are in the [columns]"
df.loc["a", (6, "two")] # Assertion Error : assert retval.ndim == self.ndim

Expected Behavior

However, the code below works fine(as expected)

  1. df.loc["a", "Two"]
  2. df.loc[:, "Two"]
  3. df.loc[:, [(6, "two")]]
  4. df.loc["a", [(6, "two")]]

Either, the syntax should work regardless of the datatype of the column_name, like in our example : tuple, or else the module should raise a exception or error with a clear information saying that the tuple based column name has to be changed.

I have also checked the above scenario, with other methods.
Providing a single or multiple tuple based columne(s) results a data frame without error as in the above (3) (4)
That could recommended along with the error statement, This could save a lot of time to the end user

Installed Versions

INSTALLED VERSIONS

commit : 2e218d1
python : 3.10.1.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.19045
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 12, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : English_United States.1252

pandas : 1.5.3
numpy : 1.24.0
pytz : 2022.7.1
dateutil : 2.8.2
setuptools : 58.1.0
pip : 21.2.4
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.2
html5lib : None
pymysql : None
psycopg2 : 2.9.6
jinja2 : 3.1.2
IPython : 8.12.0
pandas_datareader: None
bs4 : 4.12.2
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.2
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.10.0
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None
tzdata : 2022.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIndexingRelated to indexing on series/frames, not to indexes themselves

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions