鉴于此 MultiIndex 数据框:
arrays = [np.array(['A', 'A', 'B', 'B', 'C', 'C']),
np.array(['one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(6), index=arrays, columns=['col1'])
我想向外部索引中的每一行添加一个新行(内部索引)。
df.loc[(slice(None),'three'),:] = {'A':3, 'B':4, 'C':5}
但是这给了我一个错误: KeyError: '三'
我怎样才能做到这一点?
编辑:该行中的所有值都不相同。
最佳答案
MultiIndex.from_product
+ 重建索引
a, b = df.index.levels
res = df.reindex(pd.MultiIndex.from_product([a, [*b, 'three']]))
res[res.index.get_level_values(1) == 'three'] = 3
col1
A one -1.011201
two 0.376914
three 3.000000
B one 0.465666
two -0.634804
three 3.000000
C one -0.348338
two 1.295683
three 3.000000
更新此答案以说明您希望添加特定值。用这段代码替换最后一行:
d = {'A':3, 'B':4, 'C':5}
s = res.index.get_level_values(0).map(d)
res.col1.where(res.col1.notnull(), s.values)
A one -2.542087
two 0.966193
three 3.000000
B one -0.126671
two 0.864258
three 4.000000
C one 0.063544
two -0.401936
three 5.000000
Name: col1, dtype: float64
关于python - 将新行添加到 MultiIndex DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490336/