REGR: setitem with part of a MultiIndex raises · Issue #54875 · pandas-dev/pandas (original) (raw)

On 2.0.x:

df = pd.DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6, 'd': 7}).set_index(['a', 'b', 'c'])
ser = pd.Series(8, index=df.index.droplevel('c'))

print(df)
#        d
# a b c
# 1 3 6  7
# 2 4 6  7
# 3 5 6  7

print(ser)
# a  b
# 1  3    8
# 2  4    8
# 3  5    8
# dtype: int64

df['d'] = ser
print(df)
#        d
# a b c
# 1 3 6  8
# 2 4 6  8
# 3 5 6  8

On main and 2.1.0rc this raises:

AssertionError: Length of new_levels (2) must be same as self.nlevels (3)

A git bisect points at

commit ac3153b30a611d2593b002ca5d9ff22a2bb30af0
Author: Luke Manley <lukemanley@gmail.com>
Date:   Mon Jul 10 13:51:37 2023 -0400

    PERF: MultiIndex set and indexing operations (#53955)
    
    * PERF: MultiIndex set and indexing ops
    
    * whatsnew
    
    * convert to generator

 doc/source/whatsnew/v2.1.0.rst |  1 +
 pandas/_libs/index.pyx         | 17 +++++++++--------
 pandas/core/indexes/multi.py   | 13 +++++++++++++
 3 files changed, 23 insertions(+), 8 deletions(-)

cc @lukemanley