请查看以下简单场景,如果我做错了什么,或者这可能是 Pandas MultiIndex 数据帧中的错误,请告诉我?
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 级多索引的类似情况进行比较:
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 级多索引案例:
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 级多索引数据帧的情况下会出现这种偏差行为呢?请注意,在使用 pd.concat 而不是 df.loc 添加行时,我发现了相同的行为。
另请注意,仅对于 2 级多索引数据帧,语句:
df.loc[ ( "x", "y" ) ] = 1, 2
生成 ValueError:"无法使用长度与值不同的多索引选择索引器进行设置"。
使用 Python 3.6 (x64( 和 Pandas 0.20.3。
您很接近,需要:
才能选择所有列:
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