Creating DataFrame from Dictionary DataFrames

I have a Dictionary DataFrames where the keys are supposed to make sense:

In [32]: x = pd.DataFrame(dict(foo=[1,2,3], bar=[4,5,6])).set_index('foo')
In [33]: y = pd.DataFrame(dict(foo=[7,8,9], bar=[10,11,12])).set_index('foo')
In [34]: z = dict(x=x, y=y)

      

What looks like:

In [43]: x
Out[43]: 
     bar
foo     
1      4
2      5
3      6

In [44]: y
Out[44]: 
     bar
foo     
7     10
8     11
9     12

      

Is there a good way to get the following DataFrame:

    foo  bar
x   1    4
    2    5
    3    6
y   7    10
    8    11
    9    12

      

+3


source to share


1 answer


You can use concat

for this and the dictionary keys will automatically be used for the new index level:

In [6]: z = dict(x=x, y=y)

In [7]: pd.concat(z)
Out[7]:
       bar
  foo
x 1      4
  2      5
  3      6
y 7     10
  8     11
  9     12

      



You can also give this new index a name using an argument names

concat

(for example names=['key']

).

+3


source







All Articles