【发布时间】: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