从嵌套字典创建Multiindex Panda Dataframe

时间:2020-10-21 12:56:25

标签: python pandas dataframe dictionary nested

我有一个这样的目录:

dict = {'Filter1':{'Method1':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}},
                   'Method2':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}}},
        'Filter2':{'Method1':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}},
                   'Method2':{'Fuction1':{'Value1': 1, 'Value2': 2},
                              'Fuction2':{'Value1': 1, 'Value2': 2}}}}

我想以这种形状创建一个数据框:

                      Filter1         Filter2
                Method1   Method2   Method1  Method2
Function1 Value1   1        1          1         1
          Value2   2        2          2         2
Function2 Value1   1        1          1         1
          Value2   2        2          2         2

我该怎么做?我能找到的所有帖子都只引用了两个子行或子列,但从未引用过。 谢谢大家!

到目前为止,我尝试了这种方法:

df = pd.DataFrame.from_dict({(i, j): dict[i][j]
                         for i in dict.keys()
                         for j in dict[i].keys()
                         },
                        orient='index')

女巫给了我这个结果:

                                       Fuction1                    Fuction2
Filter1 Method1  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
        Method2  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
Filter2 Method1  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}
        Method2  {'Value1': 1, 'Value2': 2}  {'Value1': 1, 'Value2': 2}

但是我希望交换行和列,并将Value1和Value2作为行名

1 个答案:

答案 0 :(得分:1)

您要1)整理字典,2)将其加载到数据框中,3)重新设置数据框的格式。

import cv2
import numpy as np
import matplotlib.pyplot as plt
import pyrealsense2 as rs
print("Environment Ready")

pipe = rs.pipeline()
cfg = rs.config()
cfg.enable_device_from_file("../data/filename.bag")
profile = pipe.start(cfg)

colorizer = rs.colorizer()

frame = 0

while True:
    # pipe.wait_for_frames()

    frameset = pipe.wait_for_frames()
    frame += 1
    color_frame = frameset.get_color_frame()

    color_image = np.asanyarray(color_frame.get_data())

    cv2.imwrite("./bag_images/Bag_1_"+str(frame)+".jpg",color_image)
    print(f"Frame Saved {frame}")