首页 > 解决方案 > 使用双键多索引在 Pandas DataFrame 中插入行失败

问题描述

请检查以下简单场景,如果我做错了什么,或者这可能是 Pandas MultiIndex DataFrames 中的错误,请告诉我?

index = pd.MultiIndex.from_tuples((), names=[ "i1", "i2" ] )
df = pd.DataFrame( index = index, columns = [ "c1", "c2" ] )
df
        c1  c2
i1  i2

结果是一个空数据框,具有 2 级多索引 (i1, i2) 和 2 列 (c1, c2),如上所示。现在将第一行插入此数据框中:

df.loc[ ( "x", "y" ) ] = 1
df
        c1  c2  y
i1  i2          
x       NaN NaN 1.0

这个结果出乎我的意料。它使用应该在索引 i2 中插入的值插入一个新行(正确)和一个名为“y”的新列(在我看来不正确),并且没有为 i2、c1 和 c2 分配任何值。

将此与 1 级 MultiIndex 的类似情况进行比较:

index = pd.MultiIndex.from_tuples((), names=[ "i1" ] )
df = pd.DataFrame( index = index, columns = [ "c1", "c2" ] )
df
    c1  c2
i1      

df.loc[ "x" ] = 1, 2
df
    c1  c2
i1      
x   1   2

在这里,我们找到一个新行“x”,索引中的索引值,列中的数据值,并且没有添加额外的列。

或者更相关的 3 级 MultiIndex 案例:

index = pd.MultiIndex.from_tuples((), names=[ "i1", "i2", "i3" ] )
df = pd.DataFrame( index = index, columns = [ "c1", "c2" ] )
df
            c1  c2
i1  i2  i3  

df.loc[ ("x", "y", "z") ] = 1, 2
df
            c1  c2
i1  i2  i3      
x   y   z   1   2

同样在这种情况下,插入一个新行(“x”、“y”、“z”),其中包含索引中的索引值、列中的数据值,并且没有添加额外的列。

那么为什么在 2 级 MultiIndex DataFrame 的情况下会出现这种异常行为呢?请注意,在使用 pd.concat 而不是 df.loc 添加行时,我发现了相同的行为。

另请注意,仅对于 2 级 MultiIndex DataFrame 语句:

df.loc[ ( "x", "y" ) ] = 1, 2

生成 ValueError:“无法使用长度与值不同的多索引选择索引器进行设置”。

使用 Python 3.6 (x64) 和 Pandas 0.20.3。

标签: pandasdataframeinsertrowmulti-index

解决方案


您很接近,需要:选择所有列:

df.loc[ ( "x", "y" ), :] = 1
print (df)
       c1  c2
i1 i2        
x  y    1   1

df.loc[ ( "x", "y" ), :] = 1,2
print (df)
       c1  c2
i1 i2        
x  y    1   2

推荐阅读