-
-
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
#Create simple multilevel index with two levels (note one entry on level 1 is None):
index = pd.MultiIndex.from_tuples([('A', 'a1'), ('A', 'a2'), ('B', 'b1'), ('B', None)])
#Create dataframe with said index:
pd.DataFrame([(0, 6), (1, 5), (2, 4), (3, 7)], index=index)
# 0 1
#A a1 0 6
# a2 1 5
#B b1 2 4
# NaN 3 7
#Now it is possible to enlarge this dataframe with a new index entry provided none of the keys are None:
df.loc[('B', 'b2'),:] = [10, 11]
# 0 1
# A a1 0.0 6.0
# a2 1.0 5.0
# B b1 2.0 4.0
# NaN 3.0 7.0
# b2 10.0 11.0
#However this will throw a KeyError:
df.loc[('A', None),:] = [12, 13]
#Also doesn't work with an index slice:
idx = pd.IndexSlice
#this will throw a KeyError:
df.loc[idx['A', None],:] = [12, 13]
Issue Description
It is possible to enlarge a dataframe with a multilevel indexes by providing the new key as parameters to df.loc[...]
It is also possible to create entries to multilevel indices that have None as the key i.e. df.loc[('A', None),...]
It is not possible to enlarge a dataframe with a multilevel index if one or more of the keys is None.
Expected Behavior
Building on the example above,
df.loc[('A', None),:] = [12, 13]
should result in the following:
# A a1 0.0 6.0
# a2 1.0 5.0
# NaN 12.0 13.0
# B b1 2.0 4.0
# NaN 3.0 7.0
# b2 10.0 11.0
Installed Versions
INSTALLED VERSIONS
commit : d9cdd2e
python : 3.10.6.final.0
python-bits : 64
OS : Darwin
OS-release : 23.5.0
Version : Darwin Kernel Version 23.5.0: Wed May 1 20:19:05 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T8112
machine : arm64
processor : arm
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8
pandas : 2.2.2
numpy : 1.26.4
pytz : 2024.1
dateutil : 2.9.0.post0
setuptools : 63.2.0
pip : 24.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 : 3.1.4
IPython : None
pandas_datareader : None
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.8.4
numba : 0.59.1
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.13.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : 2024.1
qtpy : None
pyqt5 : None