How to create a Pandas DataFrame from dictionary of dataframes? How to create a Pandas DataFrame from dictionary of dataframes? pandas pandas

How to create a Pandas DataFrame from dictionary of dataframes?


This should do it:

import pandas as pddf1 = pd.DataFrame({    "col1":['val1','val3'],    "col2":['val2','val3'],    "col3":['val3','val5']})df2 = pd.DataFrame({    "col1":['val7','val3'],    "col2":['val2','val3'],    "col3":['val3','val5']})pd_dct = {"A": df1, "B": df2}# adding the key in for key in pd_dct.keys():    pd_dct[key]['key'] = key # concatenating the DataFramesdf = pd.concat(pd_dct.values())

Alternatively, we can also do this in one line with:

pd.concat(pd_dct, axis=0).reset_index(level=0).rename({'level_0':'key'}, axis=1)