Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a DataFrame to a multiindex DataFrame?

Suppose that I have the DataFrames

In [1]: a=pd.DataFrame([[1,2],[3,4],[5,6],[7,8]],  
   ...:     index=pd.MultiIndex.from_product([('A','B'),('d','e')]))                                    

In [2]: a                                                                                               
Out[2]: 
     0  1
A d  1  2
  e  3  4
B d  5  6
  e  7  8

In [3]: b=pd.DataFrame([[9,10],[11,12]],index=('d','e'))                                                

In [4]: b                                                                                               
Out[4]: 
    0   1
d   9  10
e  11  12

and I want to append b to a, with the subindex C, producing the DataFrame

      0   1
A d   1   2
  e   3   4
B d   5   6
  e   7   8
C d   9  10
  e  11  12

I tried

In [5]: a.loc['C'] = b 

but got

TypeError: 'int' object is not iterable

How do I do it?

like image 933
bmello Avatar asked Sep 03 '25 02:09

bmello


2 Answers

Assign a new value to b , then set_index and swaplevel before append to a

a.append(b.assign(k='C').set_index('k',append=True).swaplevel(0,1))
Out[33]: 
      0   1
A d   1   2
  e   3   4
B d   5   6
  e   7   8
C d   9  10
  e  11  12
like image 91
BENY Avatar answered Sep 04 '25 23:09

BENY


First update b's index to match the same levels as a, then concat:

b.index = pd.MultiIndex.from_arrays([('C','C'), ('d','e')])
pd.concat([a,b]))])
like image 23
Kyle Avatar answered Sep 05 '25 01:09

Kyle