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
We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.
We can create pandas dataframe by using tuples.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With