【发布时间】:2018-02-08 15:04:33
【问题描述】:
我已经尝试了我为嵌套字典找到的所有可能的解决方案,但无法使任何工作,因为我的字典是列表和字典的组合:
我从 Oandapyv20 得到这个结果:
{
"positions": [
{
"instrument": "USD_TRY",
"long": {
"units": "19028",
"averagePrice": "3.96627",
"pl": "2619.1369",
"resettablePL": "2619.1369",
"financing": "-212.5055",
"guaranteedExecutionFees": "0.0000",
"tradeIDs": [
"173664",
"173783",
"173785",
"173787",
"176966",
],
"unrealizedPL": "-267.6793"
},
"short": {
"units": "0",
"pl": "0.0000",
"resettablePL": "0.0000",
"financing": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "0.0000"
},
"pl": "2619.1369",
"resettablePL": "2619.1369",
"financing": "-212.5055",
"commission": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "-267.6793",
"marginUsed": "951.4000"
},
{
"instrument": "USD_MXN",
"long": {
"units": "7750",
"averagePrice": "19.37866",
"pl": "122.5599",
"resettablePL": "122.5599",
"financing": "-48.8715",
"guaranteedExecutionFees": "0.0000",
"tradeIDs": [
"212492",
"212494",
"212496",
],
"unrealizedPL": "-41.5788"
},
"short": {
"units": "0",
"pl": "0.0000",
"resettablePL": "0.0000",
"financing": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "0.0000"
},
"pl": "122.5599",
"resettablePL": "122.5599",
"financing": "-48.8715",
"commission": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "-41.5788",
"marginUsed": "387.5000"
},
{
"instrument": "USD_NOK",
"long": {
"units": "0",
"pl": "0.0000",
"resettablePL": "0.0000",
"financing": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "0.0000"
},
"short": {
"units": "-13200",
"averagePrice": "7.65519",
"pl": "4906.3941",
"resettablePL": "4906.3941",
"financing": "-90.9699",
"guaranteedExecutionFees": "0.0000",
"tradeIDs": [
"214255",
"214257",
"214259",
"214281"
],
"unrealizedPL": "-390.0560"
},
"pl": "4906.3941",
"resettablePL": "4906.3941",
"financing": "-90.9699",
"commission": "0.0000",
"guaranteedExecutionFees": "0.0000",
"unrealizedPL": "-390.0560",
"marginUsed": "132.0000"
}
],
"lastTransactionID": "228573"
}
}
如何将其转换为 Pandas DataFrame?
例如这给出了一个错误:
df = pd.DataFrame.from_dict(x,orient='index')
TypeError: Expected list, got str
还有这个:
reform = {(level1_key, level2_key, level3_key): values
for level1_key, level2_dict in x.items()
for level2_key, level3_dict in level2_dict.items()
for level3_key, values in level3_dict.items()}
AttributeError: 'list' object has no attribute 'items'
是否可以在不求助于包括 for 循环和 try & except 在内的绝望尝试的情况下将上述内容输入到 DataFrame 中?
提前致谢
【问题讨论】:
标签: python python-3.x pandas dictionary dataframe