将一个DataFrame插入/附加到一个多级索引的DataFrame中

4
我想通过追加另一个DataFrame来扩大(添加新索引到)MultiIndex DataFrame。
这是两个DataFrame:
DF1 - pop:
mi = pd.MultiIndex.from_tuples([('in','a'),('in','b'),('v','t')],names=['Scope','Name'])
mc = pd.MultiIndex.from_tuples([(0,1),(0,2),(0,3)],names=['Gen','N'])
pop = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],index=mi,columns=mc)

这句话的意思是:“这就导致了:”
Gen         0
N           1  2  3
Scope Name
in    a     1  2  3
      b     4  5  6
v     t     7  8  9

DF2 - res :
mi = pd.MultiIndex.from_tuples([('in','a'),('in','b'),('res','c'),('res','d')],names=['Scope','Name'])
res = pd.DataFrame([[1,2,3],[4,5,6],[10,20,30],[11,22,33]],index=mi,columns=[1,2,3])

这句话的意思是:“给出:”。
             1   2   3
Scope Name
in    a      1   2   3
      b      4   5   6
res   c     10  20  30
      d     11  22  33

我想把“res”的“res”(命名不好,抱歉)添加到“pop”中(其中“res”索引仍不存在)。 我尝试了以下方法但没有成功:
pop[0].loc['res'] = res['res']
pop.loc['res',0] = res['res']

两者都导致了`KeyError: 'res'`。我还尝试过使用`pd.concat`或`append`,但结果不佳(我不想定义一个新的DataFrame,而是扩大原始pop)。感谢您的帮助。
解决方法: 我成功地获得了所需的DataFrame,但不是“inplace”。
mi_col = pd.concat([res.loc['res']],keys=[0],axis=1) #Select 'res' index and add the '0' level to column
mi_ind = pd.concat([mi_col],keys=['res']) #Re-adding the 'res' level to index (drop during the previous selection)
pop = pd.concat([pop, mi_ind]) #Concatenating the 2 DataFrame into a new one

我仍然对不生成新的数据框解决方案感兴趣。
1个回答

0

我仍然对不生成新的DataFrame的解决方案感兴趣。

为什么这被认为是一种优势还不清楚。原地操作并不是固有更好的选择,甚至在这里可能不可行;例如,请参见此答案。如下,您可以使用reindex然后通过loc进行赋值,但reindex会创建一个新的对象。

res_res = res.loc[['res']]

# adds res index with NaN values since res values not populated
pop = pop.reindex(pop.index.union(res_res.index))  

# assign values
pop.loc['res'] = res_res

# convert to int from float due to previous NaN values
pop = pop.astype(int)

print(pop)

Gen          0        
N            1   2   3
Scope Name            
in    a      1   2   3
      b      4   5   6
res   c     10  20  30
      d     11  22  33
v     t      7   8   9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接