BUG: Pandas 2.0.0 may raise InvalidIndexError when assigning a column with an enum as label · Issue #52652 · pandas-dev/pandas (original) (raw)
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
from enum import Enum import pandas as pd
class E(Enum): X1 = "x1" X2 = "x2"
it works with both Pandas 1.5.3 and 2.0.0
df = pd.DataFrame({"a": [10, 11]}) df[E.X1] = [20, 21]
it works with Pandas 1.5.3, it fails with Pandas 2.0.0
df = pd.DataFrame(index=pd.RangeIndex(2)) df[E.X1] = [20, 21]
it works with Pandas 1.5.3, it fails with Pandas 2.0.0
df = pd.DataFrame(index=pd.Index([0, 1])) df[E.X1] = [20, 21]
it works with Pandas 1.5.3, it fails with Pandas 2.0.0
df = pd.DataFrame() df[E.X1] = [20, 21]
Error:
Traceback (most recent call last):
File "./dev/try_pandas.py", line 14, in <module>
df[E.X1] = [20, 21]
File "./venv/src/pandas/pandas/core/frame.py", line 3969, in __setitem__
self._set_item(key, value)
File "./venv/src/pandas/pandas/core/frame.py", line 4177, in _set_item
self._set_item_mgr(key, value)
File "./venv/src/pandas/pandas/core/frame.py", line 4129, in _set_item_mgr
loc = self._info_axis.get_loc(key)
File "./venv/src/pandas/pandas/core/indexes/range.py", line 349, in get_loc
self._check_indexing_error(key)
File "./venv/src/pandas/pandas/core/indexes/base.py", line 5760, in _check_indexing_error
raise InvalidIndexError(key)
pandas.errors.InvalidIndexError: E.X1
Issue Description
Pandas 2.0.0 may raise InvalidIndexError when assigning a column with an enum as label, if the DataFrame is empty.
Expected Behavior
The code shouldn't break, as it was with Pandas 1.5.3.
After using git bisect
, it appears that the issue started with #49637
Installed Versions
INSTALLED VERSIONS
commit : be170fc
python : 3.10.8.final.0
python-bits : 64
OS : Linux
OS-release : 3.10.0-1160.42.2.el7.x86_64
Version : #1 SMP Tue Aug 31 20:15:00 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 2.1.0.dev0+515.gbe170fc
numpy : 1.24.2
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.6.1
pip : 23.0.1
Cython : 0.29.34
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
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