簡體   English   中英

將嵌套字典轉換為 dataframe

[英]Convert nested dictionary to a dataframe

對於我擁有的一些股票數據,我正在嘗試將嵌套字典轉換為 pandas df。 我正在抓取的數據出現在字典中,如下所示。 抱歉,這是一個很長的片段,我想包含所有字段以避免錯誤地剪切它,另外我可能想在以后包含更多。

Data = [{'heading': {'key': 'history.instrument', 'context': {'quantityPrecision': 8, 'baseCode': None, 'prettyName': 'Coca-Cola', 'precision': 2, 'treeType': 'STOCK', 'instrument': 'KO', 'instrumentBadge': None, 'instrumentCode': 'KO_US_EQ'}, 'meta': None}, 'subHeading': {'key': 'history.order.filled.buy', 'context': {'quantityPrecision': 8, 'amount': 10.0, 'quantity': 0.245264, 'amountPrecision': 2}, 'meta': None}, 'mainInfo': {'key': 'history.currency-amount', 'context': {'amount': 10.0, 'currency': 'GBP'}, 'meta': None}, 'additionalInfo': {'key': 'history.order.status.filled', 'context': None, 'meta': {'colour': 'ACCENT', 'uppercase': True, 'multiline': False}}, 'date': '2021-08-26T16:45:10+03:00', 'detailsPath': '/orders/1514731569'}, {'heading': {'key': 'history.instrument', 'context': {'quantityPrecision': 8, 'baseCode': None, 'prettyName': 'First Solar', 'precision': 2, 'treeType': 'STOCK', 'instrument': 'FSLR', 'instrumentBadge': None, 'instrumentCode': 'FSLR_US_EQ'}, 'meta': None}, 'subHeading': {'key': 'history.order.filled.buy', 'context': {'quantityPrecision': 8, 'amount': 11.0, 'quantity': 0.160216, 'amountPrecision': 2}, 'meta': None}, 'mainInfo': {'key': 'history.currency-amount', 'context': {'amount': 11.0, 'currency': 'GBP'}, 'meta': None}, 'additionalInfo': {'key': 'history.order.status.filled', 'context': None, 'meta': {'colour': 'ACCENT', 'uppercase': True, 'multiline': False}}, 'date': '2021-08-26T16:45:09+03:00', 'detailsPath': '/orders/1514731500'}

我希望 output 在 dataframe 中如下所示。

期望的輸出df

我一直試圖將嵌套字典中的輸出數據轉換為 pandas dataframe 所以它對我來說更有用。

如果我嘗試將數據直接放入 dataframe 使用:

data_2 = pd.DataFrame(Data)

我得到這個 output。

電流輸出

顯然,在轉換為 dataframe 時我需要整理數據,但我無法正確設置。

您可以遍歷Data object 中主列表中的每個項目,然后選擇您需要的部分:

data_list=[]

for item in Data:
        print(item)
        data_list.append([item['heading']['context']['prettyName'], item['heading']['context']['instrument'], item['subHeading']['context']['quantity']])

df = pd.DataFrame(data_list, columns=['prettyName','instrument','quantity'])

只需添加該邏輯即可獲得剩余的列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM