简体   繁体   中英

How to convert a dictionary to Pandas df?

I have tried this following code to get live data from an api.

feed_opened = False

def event_handler_feed_update(tick_data):  
    print(tick_data)  
    # print("feed event: {0}".format(time.strftime('%d-%m-%Y %H:%M:%S')) + str(tick_data))
    # dctmessage = {k:[v] for k,v in tick_data.items()}
    df1 = pd.DataFrame.from_dict(tick_data)
    # df1.to_csv("E:/Python/tickdata.csv",mode="a", index=False)
    print (df1)

def open_callback():
    global feed_opened
    feed_opened = True

api.start_websocket(subscribe_callback=event_handler_feed_update, socket_open_callback=open_callback)

while(feed_opened==False):
    pass

api.subscribe("CDS|5316", feed_type="d")

I have tried to convert tick_data to pandas dataframe. But getting the following output....

ERROR:websocket:error from callback <bound method NorenApi.__on_data_callback of <api_helper.ShoonyaApiPy object at 0x00000000056FCD00>>: If using all scalar values, you must pass an index
{'t': 'dk', 'e': 'CDS', 'tk': '5316', 'ts': 'USDINR24DEC21C76', 'pp': '4', 'ls': '1', 'ti': '0.0025', 'lp': '0.3075', 'pc': '-33.15', 'ft': '1639640923', 'o': '0.4225', 'h': '0.4250', 'l': '0.2725', 'c': '0.4600', 'ap': '0.3550', 'v': '13390', 'ltq': '2', 'ltt': '13:17:41', 'tbq': '2289', 'tsq': '1163', 'bp1': '0.3000', 'sp1': '0.3075', 'bp2': '0.2975', 'sp2': '0.3100', 'bp3': '0.2950', 'sp3': '0.3125', 'bp4': '0.2875', 'sp4': '0.3250', 'bp5': '0.2850', 'sp5': '0.3275', 'bq1': '21', 'sq1': '18', 'bq2': '103', 'sq2': '1', 'bq3': '50', 'sq3': '150', 'bq4': '1', 'sq4': '18', 'bq5': '20', 'sq5': '24', 'bo1': '2', 'so1': '1', 'bo2': '2', 'so2': '1', 'bo3': '1', 'so3': '2', 'bo4': '1', 'so4': '3', 'bo5': '2', 'so5': '3', 'uc': '0.7950', 'lc': '0.1250', 'oi': '35759'}

How can I make proper dataframe?

This should do the trick:

pd.DataFrame.from_records([tick_data])

Let's assume you have a dictionary like: d = {'Saha':1,'Sourav':2,'family': 3} then, we have to extract dictionary items like this dict_items = d.items() Now convert the dict_items into an list item_list = list(dict_items) Finally,Convert the list into a dataframe using pandas df = pd.DataFrame(item_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM