Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a DataFrame from a dictionary of DataFrames

Tags:

python

pandas

I have a dictionary of DataFrames, where the keys are assumed to be meaningful:

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)

Which 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 nice way to get the following DataFrame:

    foo  bar
x   1    4
    2    5
    3    6
y   7    10
    8    11
    9    12
like image 478
LondonRob Avatar asked Jul 16 '15 16:07

LondonRob


People also ask

Can we create DataFrame from dictionary?

Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.

How do you create a DataFrame from a dictionary list?

Use from_dict(), from_records(), json_normalize() methods to convert list of dictionaries (dict) to pandas DataFrame. Dict is a type in python to hold key-value pairs. Key is used as a column name and value is used for column value when we convert dict to DataFrame.

What method creates a pandas DataFrame from a dictionary?

Create dataframe with Pandas from_dict() Method If that sounds repetitious, since the regular constructor works with dictionaries, you can see from the example below that the from_dict() method supports parameters unique to dictionaries. In the code, the keys of the dictionary are columns. The row indexes are numbers.

Can we create DataFrame using dictionary of tuples?

We can create pandas dataframe by using tuples.


1 Answers

You can use concat for this, and the keys of the dictionary will automatically be used for a 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 level a name using the names argument of concat (eg names=['key']).

like image 167
joris Avatar answered Sep 17 '22 22:09

joris