用熊猫拼合嵌入式密钥

布鲁斯·哈里森(Bruce Harrison)

我正在尝试(未成功)为嵌入式字典键创建单独的列。Dict数据如下所示:

{'averagePrice': 32.95,
  'currentDayProfitLoss': 67.2,
  'currentDayProfitLossPercentage': 0.02,
  'instrument': {'assetType': 'EQUITY', 'cusip': '902104108', 'symbol': 'IIVI'},
  'longQuantity': 120.0,
  'marketValue': 4021.2,
  'settledLongQuantity': 120.0,
  'settledShortQuantity': 0.0,
  'shortQuantity': 0.0}]

“ instrument”键是我试图压平到列(即assetType,cusip,symbol)的键。这是我上次尝试的代码,仍然没有单独的列

data = accounts_data_single
my_dict = data
headers = list(my_dict['securitiesAccount']['positions'])
dict1 = my_dict['securitiesAccount']['positions']


mypositions = pd.DataFrame(dict1)
pd.concat([mypositions.drop(['instrument'], axis=1), mypositions['instrument'].apply(pd.Series)], axis=1)
mypositions.to_csv('Amer_temp.csv')

任何建议,不胜感激

我试图在所有列中获取嵌套键/字段名称,然后在行中获取所有库存位置。除了嵌套的“ instrument”键都在同一列中之外,以上代码非常有用

averagePrice  currentDayProfitLoss  ...  assetType  cusip  symbol
22.5          500                   ...  Equity     013245  IIVI
450           250                   ...  Equity     321354  AAPL
etc
压迫者

您是否要这样做:

pd.DataFrame(d).assign(**pd.DataFrame([x['instrument'] for x in d])).drop(columns='instrument')                                                                                      

输出:

   averagePrice  currentDayProfitLoss  currentDayProfitLossPercentage  longQuantity  marketValue  settledLongQuantity  settledShortQuantity  shortQuantity assetType      cusip symbol
0         32.95                  67.2                            0.02         120.0       4021.2                120.0                   0.0            0.0    EQUITY  902104108   IIVI
1         31.95                  63.2                            0.01         100.0       3021.2                100.0                   0.0            0.0    EQUITY  802104108   AAPL

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章