繁体   English   中英

Python,嵌套字典到数据框

[英]Python, Nested Dictionary to Dataframe

在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'}]}}

放入具有类似以下内容的列的DataFrame中:

name  strike  date  type   last  ask bid  change  volume  volatility 

谢谢

我将遍历您的结构并将其转换为大熊猫可以自动识别的新格式,例如一系列字典。 您必须根据自己的确切需求对其进行自定义,但这是基于当前数据结构的概念证明。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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