Thanks to visit codestin.com
Credit goes to github.com

Skip to content

BUG: Misleading KeyError output on dataframe.drop(columns=['Col1', 'Col2']) when columns to drop are not present #42881

Closed
@robinstauntoncollins

Description

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

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

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

df = pd.DataFrame({
     'Col1': ['one', 'two'],
     'Col2': ['three', 'four']
})

df.drop(columns=['Col3', 'Col4'])

Actual Output:

KeyError: "['Col3' 'Col4'] not found in axis"

(comma missing between list items)

Problem description

When trying to drop a list of columns that don't exist in the dataframe the key error shows a list without the comma separating the items in the list. This leads to the confusion that the list I passed into the drop() function was wrong whereas it was correct but the KeyError message was wrong.

Expected Output

KeyError: "['Col3', 'Col4'] not found in axis"

(with comma separating items in list)

Output of pd.show_versions()

INSTALLED VERSIONS

commit : c7f7443
python : 3.7.9.final.0
python-bits : 64
OS : Windows
OS-release : 10
Version : 10.0.18362
machine : AMD64
processor : Intel64 Family 6 Model 142 Stepping 12, GenuineIntel
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.None

pandas : 1.3.1
numpy : 1.21.1
pytz : 2021.1
dateutil : 2.8.2
pip : 21.0.1
setuptools : 47.1.0
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 : None
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : 3.0.7
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : 2.0.1
xlwt : None
numba : None

Metadata

Metadata

Assignees

Labels

BugError ReportingIncorrect or improved errors from pandasIndexingRelated to indexing on series/frames, not to indexes themselves

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions