在python中转换包含多级字典的嵌套列表

时间:2018-09-20 07:29:54

标签: python python-3.x pandas dictionary nested-lists

我有一个json文件,其中包含包含多级字典的嵌套列表。我正在尝试从此数据创建python DataFrame。

Loading data:

data = []
with open('TREC_blog_2012.json') as f:
for line in f:
    data.append(json.loads(line))

数据输出:

IN LIST FORMAT: data[0] 

{'id': '1d3bc37004e71da2816dbfda8df90746',
'article_url': 'https://www.washingtonpost.com/express/wp/2012/01/03/month-of-muscle/',
'title': 'Month of Muscle',
'author': 'Vicky Hallett',
'published_date': 1325608933000,
'contents': [{'content': 'Express', 'mime': 'text/plain', 'type': 'kicker'},
{'content': 'Month of Muscle', 'mime': 'text/plain', 'type': 'title'},
{'content': 'By Vicky Hallett', 'mime': 'text/plain', 'type': 'byline'},
{'content': 1325608933000, 'mime': 'text/plain', 'type': 'date'},
{'content': 'SparkPeople trainer Nicole Nichols asks for only 28 days to get you into shape',
'mime': 'text/plain',
'type': 'deck'},
{'fullcaption': 'Nicole Nichols, front, chose backup exercisers with strong but realistic physiques to make the program less intimidating.',
'imageURL': 'http://www.expressnightout.com/wp-content/uploads/2012/01/SparkPeople28DayBootcamp.jpg',
'mime': 'image/jpeg',
'imageHeight': 201,
'imageWidth': 300,
'type': 'image',
'blurb': 'Nicole Nichols, front, chose backup exercisers with strong but realistic physiques to make the program less intimidating.'},
 {'content': 'If you’ve seen a Nicole Nichols workout before, chances are it was on YouTube. The fitness expert, known as just Coach Nicole to the millions of members of <a href="http://www.sparkpeople.com" target="_blank">SparkPeople.com</a>, has filmed dozens of routines for the free health website. The popular videos showcasing her girl-next-door style, gentle encouragement and clear cueing have built such a devoted following that the American Council on Exercise and Life Fitness just named her “America’s top personal trainer to watch.”',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
{'content': '<strong>3. Prioritize.</strong> When people say they can’t fit exercise in their schedule, Nichols always asks, “How much TV do you watch?” Use your shows as a reward for your workout instead of the replacement, she suggests.',
'subtype': 'paragraph',
'type': 'sanitized_html',
'mime': 'text/html'},
{'role': '',
'type': 'author_info',
'name': 'Vicky Hallett',
'bio': 'Vicky Hallett is a freelancer and former MisFits columnist.'}],
'type': 'blog',
'source': 'The Washington Post'}

我想将此数据转换为以键为列的DataFrame类型,并将其各自的值作为行值。

但是我面临的问题是关键的“内容”包含一个多级字典值的列表,我不知道如何将其转换为合适的DataFrame值。

The method I tried:

df = pd.DataFrame(data)
test = pd.DataFrame(df['contents'][0])
test.head()

给我df ['contents']的输出为

output received for test

如果尝试上述方法,则数据对齐不正确,并且分配不正确。关于如何将目录密钥字典列表解析为适当的数据框的任何建议?

TIA:)

2 个答案:

答案 0 :(得分:1)

您可能必须从每个子词典中分别提取相关信息,然后将其分配给数据框的适当列。

这部分可以立即分配给数据框的列:

{'id': '1d3bc37004e71da2816dbfda8df90746',
'article_url': 'https://www.washingtonpost.com/express/wp/2012/01/03/month-of-muscle/',
'title': 'Month of Muscle',
'author': 'Vicky Hallett',
'published_date': 1325608933000}

但是,这部分需要首先分配给python中的字典,然后才能将这些列提取到pandas数据框中。

{'contents': [{'content': 'Express', 'mime': 'text/plain', 'type': 'kicker'}]}

因此您的代码可能如下所示:

import pandas as pd

json_file = {'id': '1d3bc37004e71da2816dbfda8df90746',
'article_url': 'https://www.washingtonpost.com/express/wp/2012/01/03/month-of-muscle/',
'title': 'Month of Muscle',
'author': 'Vicky Hallett',
'published_date': 1325608933000,
'contents': [{'content': 'Express', 'mime': 'text/plain', 'type': 'kicker'}]
            }

df = pd.DataFrame.from_dict(json_file)
my_dict = df['contents'].values[0]
for key in my_dict.keys():
    df[key] = my_dict[key]

您将不得不将此过程扩展到json文件的其他子词典(如果存在)。 假设原始json文件中的键/节点都不是子词典中的键,则此代码会将子词典的所有元素分配给数据帧中的相应列。如果数据集中有多个行/ json文件,则可以使用此过程首先将每个json转换为pandas数据框,然后可以将转换后的json(现在是数据框)追加到主要的全局数据框,每个行的行包含从单个json文件提取的信息。

答案 1 :(得分:1)

我会做这样的事情:

new_data = []
for row in data: 
    if 'contents' in row:
        for content in row['contents']:
            new_dict = dict(row)
            del new_dict['contents']

            for key, value in content.items():
                new_dict['content_{}'.format(key)] = value

            new_data.append(new_dict)
    else:
        new_data.append(row)

请注意,我为“内容”中的每个元素创建了一行数据帧。因此,您将有9行对应于data [0]中的元素。

pd.DataFrame.from_dict(new_data)

enter image description here

基本上,有两种方法可以将嵌套的dict转换为2D数据框:您可以为列表中的每个元素保留一行,但是您需要添加很多列(“内容”中包含的dict的每个元素为一列) ,列数可能会发生很大的变化,并且会变得令人头痛”),或者在“内容”中为每个元素添加一行。我认为最后一个适合您的情况。