【发布时间】:2019-03-22 07:11:03
【问题描述】:
我想通过附加另一个 DataFrame 来放大(=添加新索引)一个 MultiIndex DataFrame。
这是两个 DataFrame:
DF1 - 流行:
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 - 分辨率:
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,但不是“就地”:
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 的解决方案感兴趣。
【问题讨论】:
标签: python pandas dataframe multi-index