Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert python dictionary to pandas dataframe

I have the following data that I want convert into pandas dataframe
Input

my_dict = {'table_1': [{'columns_1': 148989, 'columns_2': 437643}], 'table_2': [{'columns_1': 3344343, 'columns_2': 9897833}]}

Expected Output

   table_name      columns_1      columns_2  
      table_1         148989         437643      
      table_2        3344343        9897833      

I tried below way but due to the loop, i can only get the last value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def convert_to_df():
  for key, value in my_dict.items():
    df = pd.DataFrame.from_dict(value, orient='columns')
    df['table_name'] = key
    
  return df

What I’m I missing?

>Solution :

Just get rid of those lists and you can feed directly to the DataFrame constructor:

pd.DataFrame({k: v[0] for k,v in my_dict.items()}).T

output:

         columns_1  columns_2
table_1     148989     437643
table_2    3344343    9897833

With the index as column:

(pd.DataFrame({k: v[0] for k,v in my_dict.items()})
   .T
   .rename_axis('table_name')
   .reset_index()
)

output:

  table_name  columns_1  columns_2
0    table_1     148989     437643
1    table_2    3344343    9897833
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading