Python将字典转换为数据帧失败

时间:2016-09-15 06:46:45

标签: python pandas dictionary dataframe

当我尝试将以下字典转换为dataframe时,python会重复每行两次。

a = [[[[130.578125, 96, 130.59375, 541],
       [130.5625, 635, 130.609375, 1055],
       [130.546875, 657, 130.625, 1917],
       [130.53125, 707, 130.640625, 1331],
       [130.515625, 1530, 130.65625, 2104]],
      [[130.578125, 96, 130.59375, 541],
       [130.5625, 635, 130.609375, 1055],
       [130.546875, 657, 130.625, 1917],
       [130.53125, 707, 130.640625, 1331],
       [130.515625, 1530, 130.65625, 2104]]],
     [[[143.34375, 5, 143.359375, 79],
       [143.328125, 142, 143.375, 129],
       [143.3125, 132, 143.390625, 137],
       [143.296875, 126, 143.40625, 118],
       [143.28125, 113, 143.421875, 125]],
      [[143.34375, 5, 143.359375, 79],
       [143.328125, 142, 143.375, 129],
       [143.3125, 132, 143.390625, 137],
       [143.296875, 126, 143.40625, 118],
       [143.28125, 113, 143.421875, 125]]]]

b = ['Mini','on']

c = dict(zip(b,a))

d = pd.DataFrame.from_dict(c)

print d

Python打印以下输出:

                                                Mini  \
0  [[130.578125, 96, 130.59375, 541], [130.5625, ...
1  [[130.578125, 96, 130.59375, 541], [130.5625, ...

                                                  on
0  [[143.34375, 5, 143.359375, 79], [143.328125, ...
1  [[143.34375, 5, 143.359375, 79], [143.328125, ...

所需的输出是:

                                                Mini  \
0  [[130.578125, 96, 130.59375, 541], [130.5625, ...

                                                  on
0  [[143.34375, 5, 143.359375, 79], [143.328125, ...

有人可以建议我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

让我们从一个例子开始

你得到了

pd.DataFrame({'Mini': [1, 1], 'on': [2, 2]})

enter image description here

何时需要

pd.DataFrame({'Mini': [1], 'on': [2]})

enter image description here

您对a的定义是列表形式的2x2x5x4数组。第一个维度被压缩为dict的值。第二个维度是长度为2的列表,我刚刚演示了将这样的字典传递给pd.DataFrame时会发生什么

要解决此问题,请将以下行与您之前定义的d

交换
    d = pd.Series(c).to_frame().T

对评论的回复
打印整个单元格内容

with pd.option_context('display.max_colwidth', -1):
    print d