请检查以下简单场景,如果我做错了什么,或者这可能是 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 级多索引的类似情况进行比较:
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。
最佳答案
你很接近,需要 :
来选择所有列:
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
关于pandas - 使用双键多索引在 Pandas DataFrame 中插入行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117642/