[英]Convert nested dictionary into dataframe
My dictionary looks like this 我的字典看起来像这样
mydict =
{240594.0: {1322.0: 1.6899999999999999, 1323.0: 1.6900000000000002, 1324.0: 1.6899999999999999, 1325.0: 1.6899999999999999, 1326.0: 1.6899999999999999, 1327.0: 1.6900000000000002, 1328.0: 1.6899999999999999, 1329.0: 1.6899999999999999, 1356.0: 1.6900000000000002, 1357.0: 1.6900000000000002, 1358.0: 1.6899999999999999, 1359.0: 1.6900000000000002, 1360.0: 1.6900000000000002, ...},
226918.0: {1322.0: 1.6900000000000002, 1323.0: 1.6899999999999999, 1324.0: 1.6900000000000002, 1325.0: 1.6899999999999999, 1326.0: 1.6900000000000002, 1327.0: 1.6899999999999999, 1328.0: 1.6900000000000002, 1329.0: 1.6899999999999999, 1352.0: 1.6900000000000002, 1353.0: 1.6900000000000002, 1354.0: 1.6899999999999999 ...}}
which is the real value of {iri_key: {week:price, week:price ...}, iri_key: {...}}
and I want to convert this dictionary into dataframe which looks like 这是{iri_key: {week:price, week:price ...}, iri_key: {...}}
的真实值,我想将此字典转换为如下所示的数据{iri_key: {week:price, week:price ...}, iri_key: {...}}
week week week ...
irikey: price price price ...
irikey: ... ... ...
in above case 在上述情况下
1322.0 ...
240594.0 1.6899999999999999 ...
226918.0 1.6900000000000002 ...
how could I do this? 我该怎么办?
As you have probably discovered, DataFrame(mydict)
is valid code. 您可能已经发现, DataFrame(mydict)
是有效的代码。 You could simply take the transpose ( .T
) to get your desired result. 您可以简单地使用移调( .T
)以获得所需的结果。
A better way, in terms of code readability and directness, is available: use the specific DataFrame constructor DataFrame.from_dict
, which has a keyword argument orient
. 就代码的可读性和直接性而言,可以使用一种更好的方法:使用特定的DataFrame构造函数DataFrame.from_dict
,它具有关键字参数orient
。
In [2]: DataFrame.from_dict(mydict, orient='index')
Out[2]:
1356 1357 1358 1359 1360 1322 1323 1324 1325 1326 1327 \
226918 NaN NaN NaN NaN NaN 1.69 1.69 1.69 1.69 1.69 1.69
240594 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69
1328 1329 1352 1353 1354
226918 1.69 1.69 1.69 1.69 1.69
240594 1.69 1.69 NaN NaN NaN
[2 rows x 16 columns]
As you can see from the example data you provided, missing values and variable lengths are handled properly. 从提供的示例数据中可以看到,正确处理了缺失值和可变长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.