2016-02-05 26 views
0

在蟒蛇需要拼合啓動這樣一個大的嵌套的字典:Python中,嵌套的字典到數據幀

{u'February 19, 2016': {'calls': [{'%change': u'0.00%', 
'ask': u'6.50', 
'bid': u'5.20', 
'change': u'0.00', 
'interest': u'10', 
'last': u'10.30', 
'name': u'LVLT160219C00044000', 
'strike': u'44.00', 
'volatility': u'62.31%', 
'volume': u'10'}]}} 

成數據幀類似於列:

name strike date type last ask bid change volume volatility 

感謝

+0

你能告訴我們你的企圖嗎? – tinySandy

+1

做一個工作的例子,輸入,大括號和支架不平衡 – jxramos

+0

@minitoto我很想,甚至還沒有接近。這個方法http://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values目前可能顯示出一些進展。 – Jameson

回答

0

我會循環你的結構,並把它轉換成熊貓可以自動識別的新格式,就像一系列的字典。 您必須根據您的確切需求對其進行定製,但這是基於當前數據結構的概念驗證。

import pandas as pd 
#your data looks something like this: 
mydict={"date1" : {"calls": [ {"change":1,"ask":4,"bid":5,"name":"x83"}, 
           {"change":3,"ask":9,"bid":2,"name":"y99"} ] }, 
     "date2" : {"calls": [ {"change":4,"ask":3,"bid":7,"name":"z32"} ] } } 

def convert(something): 
    # Convert strings to floats, unless they're really strings 
    try: return float(something) 
    except ValueError: return something 

# make an empty sequence 
dataseq = [] 
# list the fields you want from each call 
desired = ["ask","change","bid","name"] 

for thisdate in mydict.keys(): 
    # get the calls for each date 
    for thiscall in mydict[thisdate]["calls"]: 
     # initialize a new dictionary for this call with the entry date 
     d = {"date":thisdate} 
     for field in desired: 
      # get the data and convert to float if it's a float 
      d[field]=convert(thiscall[field]) 
     # add it to your sequence 
     dataseq.append(d) 
# make a dataframe 
a = pd.DataFrame(dataseq)