【问题标题】:Convert dict with variable length list of dicts to pandas dataframe将具有可变长度的字典列表的字典转换为熊猫数据框
【发布时间】:2018-12-28 10:35:37
【问题描述】:

我有一个字典,其中包含一个字典列表作为值,这些列表的长度是可变的。我尝试了很多,但无法将数据正确转换为 Pandas 数据框。

数据如下:

{key1: [{'column5': 40, 'column1': 1, 'column2': 6, 'column3': 170, 'column4': 300}], 
key2: [{'column5': 6, 'column1': 33, 'column2': 5, 'column3': 76, 'column4': 13}], 
key3: [{'column5': 7, 'column1': 44, 'column2': 2, 'column3': 67, 'column4': 13}, {'column5': 45, 'column1': 400, 'column2': 100, 'column3': 12, 'column4': 145}]}

我想要这样的框架:

      column1  column2 column3   ..
key1  1        6       170
key2  33       5       76
key3  33       2       67
key3  400      100     12
 .
 .

在使用 pd.DataFrame.from_records 和使用 orient=index 时,我会收到类似“数组必须全部长度相同”之类的错误,而当使用 orient=index 时,数据仍作为字典放置在数据框中。我尝试过的一些事情:

df = pd.DataFrame.from_dict(a, orient='index')
df.transpose() //Data is not properly placed in the dataframe

df = pd.DataFrame.from_records(dataset, orient='index') //Data is not properly placed in the dataframe

df = pd.DataFrame.from_records(dataset) //Gives error about length of arrays

df = pd.DataFrame.from_dict(dataset).T //Gives error about length of arrays

我应该怎么做?非常感谢!

【问题讨论】:

  • 你能发布你想要的数据框吗?你的字典也没有正确定义
  • 我已经编辑了原帖,希望现在更清楚了。如果没有,请告诉我。
  • 您能否将所需的数据框以文本形式发布,按照您的要求进行格式化,而不是对其进行描述?
  • 非常感谢您的链接,我已经编辑了问题。

标签: python pandas dictionary dataframe


【解决方案1】:

设置

dct = {'key1': [{'column5': 40, 'column1': 1, 'column2': 6, 'column3': 170, 'column4': 300}],'key2': [{'column5': 6, 'column1': 33, 'column2': 5, 'column3': 76, 'column4': 13}],'key3': [{'column5': 7, 'column1': 44, 'column2': 2, 'column3': 67, 'column4': 13}, {'column5': 45, 'column1': 400, 'column2': 100, 'column3': 12, 'column4': 145}]}

使用列表推导稍微重构您的输入数据集:

pd.DataFrame([{'key': k, **i} for  k, v in dct.items() for i in v])

   column1  column2  column3  column4  column5   key
0        1        6      170      300       40  key1
1       33        5       76       13        6  key2
2       44        2       67       13        7  key3
3      400      100       12      145       45  key3

为了帮助更好地理解为什么这是有效的,这里是列表理解创建的字典列表:

[{'key': 'key1', 'column5': 40, 'column1': 1, 'column2': 6, 'column3': 170, 'column4': 300}, {'key': 'key2', 'column5': 6, 'column1': 33, 'column2': 5, 'column3': 76, 'column4': 13}, {'key': 'key3', 'column5': 7, 'column1': 44, 'column2': 2, 'column3': 67, 'column4': 13}, {'key': 'key3', 'column5': 45, 'column1': 400, 'column2': 100, 'column3': 12, 'column4': 145}]

【讨论】:

    猜你喜欢
    • 2019-07-18
    • 2017-12-12
    • 2018-11-25
    • 1970-01-01
    • 2016-09-06
    • 2021-09-07
    • 2017-10-02
    • 2020-12-01
    • 2018-07-14
    相关资源
    最近更新 更多