将DataFrame插入/追加到MultiIndex DataFrame中

时间:2018-10-17 14:47:47

标签: python pandas dataframe multi-index

我想通过附加另一个DataFrame来扩大(向MultiIndex 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”(抱歉,命名不正确...)弹出(其中“ res”索引仍然不存在)。 我尝试了以下失败的尝试:

pop[0].loc['res'] = res['res']
pop.loc['res',0] = res['res']

两者都指向KeyError: 'res'。我还用pd.concat或append测试了一些东西,但是结果很差(我想不定义一个新的DataFrame而是扩大原始弹出窗口)。 预先感谢您的帮助。

WORKAROUND

我成功获得了想要的DataFrame,但没有“就地”:

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

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

1 个答案:

答案 0 :(得分:0)

  

我仍然对不会产生新的解决方案感兴趣   数据框。

尚不清楚为什么这被视为优势。就地操作本质上并不是更好,在这里甚至不可能实现。例如,参见this answer。如下所示,您可以使用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