简体   繁体   中英

Turn a dictionary of dictionaries into a dataframe

So let's say I have a dictionary that looks like this:

{Row1 : {Col1: Data, Col2: Data ..} , Row2: {Col1: Data,...},...}

Ex dictionary:

{'1': {'0': '1', '1': '2', '2': '3'}, '2': {'0': '4', '1': '5', '2': '6'}}

I was checking out pandas from_dict method with orient='index', but it's not quite what I need.

This is what I have that works:

df_pasted_data = pd.DataFrame()
for v in dictionary.values():
    # need to set the index to 0 since im passing in a basic dictionary that looks like: col1: data, col2: data
    # otherwise it will throw an error saying  ValueError: If using all scalar values, you must pass an index
    temp = pd.DataFrame(v, index=[0])
    # append doesn't happen in place so i need to set it to itself
    df_pasted_data = df_pasted_data.append(temp, ignore_index=True)

This works, but I've read online that doing appends and stuff is not very efficient, is there a better way of going about this?

make use of DataFrame() method and T (Transpose) attribute:

import pandas as pd
df_pasted_data=pd.DataFrame(dictionary).T

#output
print(df_pasted_data)
    0   1   2
1   1   2   3
2   4   5   6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM