簡體   English   中英

python 嵌套字典到 pandas DataFrame

[英]python nested dictionary to pandas DataFrame

main_dict = {
'NSE:ACC': {'average_price': 0,
             'buy_quantity': 0,
             'depth': {'buy': [{'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0},
                               {'orders': 0, 'price': 0, 'quantity': 0}],
                       'sell': [{'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0},
                                {'orders': 0, 'price': 0, 'quantity': 0}]},
             'instrument_token': 5633,
             'last_price': 2488.9,
             'last_quantity': 0,
             'last_trade_time': '2022-09-23 15:59:10',
             'lower_circuit_limit': 2240.05,
             'net_change': 0,
             'ohlc': {'close': 2555.7,
                      'high': 2585.5,
                      'low': 2472.2,
                      'open': 2575},
             'oi': 0,
             'oi_day_high': 0,
             'oi_day_low': 0,
             'sell_quantity': 0,
             'timestamp': '2022-09-23 18:55:17',
             'upper_circuit_limit': 2737.75,
             'volume': 0},
}

將字典轉換為 pandas dataframe

例如:

交易品種 last_price net_change 開盤 高 低 收盤
NSE:ACC 2488.9 0 2575 2585.5 2472.2 2555.7

我正在嘗試 pd.DataFrame.from_dict(main_dict) 但它不起作用。 請給出最好的建議。

我將首先 select 從您的 dict 中獲取必要的數據,然后將其作為輸入傳遞給pd.DataFrame()

df_input = [{
    "symbol": symbol,
    "last_price": main_dict.get(symbol).get("last_price"),
    "net_change": main_dict.get(symbol).get("net_change"),
    "open": main_dict.get(symbol).get("ohlc").get("open"),
    "high": main_dict.get(symbol).get("ohlc").get("high"),
    "low": main_dict.get(symbol).get("ohlc").get("low"),
    "close": main_dict.get(symbol).get("ohlc").get("close")
} for symbol in main_dict]

import pandas as pd
df = pd.DataFrame(df_input)

暫無
暫無

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

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