我已经尝试了我为嵌套词典找到的所有可能的解决方案,但无法获得任何工作,因为我的词典是列表和词典的组合:
我从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'
可以将上述内容输入到DataFrame中,而无需采取包括for循环在内的绝望尝试,并尝试&除了?
提前致谢
答案 0 :(得分:1)
您只需要申请pd.Series
几次
df=pd.DataFrame(d)
s=df.positions.apply(pd.Series)
v=s.short.apply(pd.Series)
t=s.long.apply(pd.Series)
Yourdf=pd.concat([df,v,s,t],1).drop(['short','positions','long'],1)