Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary of Pandas Dataframes to MultiIndex Dataframe

Tags:

python

pandas

I have a dict of Pandas Dataframes, say

d = {A: pd.DataFrame([[0, 1, 2], [2, 2, 4]),
     B: pd.DataFrame([[1, 1, 1], [2, 2, 2]}

and I'd like to change it into a MultiIndex DataFrame like this:

A 0   0, 1, 2
  1   2, 2, 4
B 0   1, 1, 1
  1   2, 2, 2
like image 517
Geoffrey Negiar Avatar asked Feb 15 '17 17:02

Geoffrey Negiar


People also ask

Can I convert dictionary to DataFrame?

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.

Can DataFrame be created from dictionary of tuples?

We can create pandas dataframe by using tuples.

How do you convert a nested dictionary to a DataFrame in Python?

Practical Data Science using PythonWe first take the list of nested dictionary and extract the rows of data from it. Then we create another for loop to append the rows into the new list which was originally created empty. Finally we apply the DataFrames function in the pandas library to create the Data Frame.

Which is faster dictionary or DataFrame?

For certain small, targeted purposes, a dict may be faster. And if that is all you need, then use a dict, for sure! But if you need/want the power and luxury of a DataFrame, then a dict is no substitute. It is meaningless to compare speed if the data structure does not first satisfy your needs.


1 Answers

Use pd.concat on the dictionary values, with the keys parameter set to the dictionary keys:

df = pd.concat(d.values(), keys=d.keys())

The resulting output:

     0  1  2
A 0  0  1  2
  1  2  2  4
B 0  1  1  1
  1  2  2  2
like image 57
root Avatar answered Sep 20 '22 16:09

root