从嵌套字典构建数据框架的最佳方法

时间:2017-12-19 12:28:26

标签: python pandas dictionary dataframe

处理完数据后,我在以下结构(嵌套字典)中保存了组级别计算:

buttonWidth  = 100; %in Pixels
buttonHeight = 100;
imPad        = 10;  %A little bit of padding

imData = imread('yourImage.jpg');  %Read your image
imSmall= imresize(imData , [buttonWidth   buttonHeight]-imPad); %Resize it.

% Place it on the button
h=uicontrol('style','pushbutton', 'units','pixels',...
            'position',[50 50 buttonWidth buttonHeight],...
            'cdata',imSmall)

字典的结构是:

{'Source1': {(1, 2): {'value1': -1.4089917877152731, 'value2': 0.15890127107708821}, (1, 3): {'value1': -3.6436438771179183, 'value2': 0.00027189114106343325}, (1, 4): {'value1': 1.3921379718956783, 'value2': 0.1639443047264573}, (2, 3): {'value1': -2.1272739953077449, 'value2': 0.033444556519261023}, (3, 4): {'value1': 5.0887284442498775, 'value2': 3.7318559307126006e-07}, (2, 4): {'value1': 2.781268059718232, 'value2': 0.0054326884405563099}}, 'Source2': {(1, 2): {'value1': 1.6065065530210021, 'value2': 0.10840303417258132}, (1, 3): {'value1': -0.67561007794063666, 'value2': 0.49941051115943469}, (1, 4): {'value1': -0.99500921260852215, 'value2': 0.31991568858488023}, (2, 3): {'value1': -2.4076869756909676, 'value2': 0.016168545874782416}, (3, 4): {'value1': -0.31851460166510093, 'value2': 0.75013768971795858}, (2, 4): {'value1': -2.7976881039916965, 'value2': 0.0052043800033575345}}}

我的目标是获取下表

Level1 - Source
Level2 - Group comparison (1,2) means compare Group 1 vs Group2
Level3 - Value of the comparison in two measurement types
  • 我认为包含价值2有点不可取,所以忽略了value2

什么是将其转换为熊猫数据框架的最佳方式。

1 个答案:

答案 0 :(得分:3)

我认为你需要:

df = pd.concat({k:pd.DataFrame(v) for k, v in d.items()})
df.columns = ['({},{})'.format(i,j) for i,j in df.columns]
print (df)
                   (1,2)     (1,3)     (1,4)     (2,3)     (2,4)         (3,4)
Source1 value1 -1.408992 -3.643644  1.392138 -2.127274  2.781268  5.088728e+00
        value2  0.158901  0.000272  0.163944  0.033445  0.005433  3.731856e-07
Source2 value1  1.606507 -0.675610 -0.995009 -2.407687 -2.797688 -3.185146e-01
        value2  0.108403  0.499411  0.319916  0.016169  0.005204  7.501377e-01