用熊猫拼合嵌入式密钥

时间:2019-12-28 22:01:57

标签: python pandas

我正在尝试(未成功)为嵌入式字典键创建单独的列。 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

2 个答案:

答案 0 :(得分:2)

这是一种执行此操作的方法。假设d是您的字典。

步骤1:将字典转换为数据框

d1 = pd.DataFrame.from_dict(d, orient='index').T.reset_index(drop=True)

步骤2:instrument列转换为数据框

d2 = d1['instrument'].apply(pd.Series)

第3步:加入第1步和第2步的输出

df = pd.concat([d1.drop('instrument', axis=1), d2], axis=1)

答案 1 :(得分:1)

您要这样做吗?

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