在Pandas数据帧中提取嵌入为字符串的嵌套JSON

时间:2015-12-04 16:21:54

标签: python json csv

我有一个CSV,其中一个字段是嵌套的JSON对象,存储为字符串。我想将CSV加载到数据帧中,并将JSON解析为附加到原始数据帧的一组字段;换句话说,提取JSON的内容并使它们成为数据帧的一部分。

我的CSV:

id|dist|json_request
1|67|{"loc":{"lat":45.7, "lon":38.9},"arrival": "Monday", "characteristics":{"body":{"color":"red", "make":"sedan"}, "manuf_year":2014}}
2|34|{"loc":{"lat":46.89, "lon":36.7},"arrival": "Tuesday", "characteristics":{"body":{"color":"blue", "make":"sedan"}, "manuf_year":2014}}
3|98|{"loc":{"lat":45.70, "lon":31.0}, "characteristics":{"body":{"color":"yellow"}, "manuf_year":2010}}

请注意,并非所有行的所有键都相同。 我希望它能产生一个与此相当的数据框:

data = {'id'     : [1, 2, 3],
        'dist'  : [67, 34, 98],
        'loc_lat': [45.7, 46.89, 45.70],
        'loc_lon': [38.9, 36.7, 31.0],
        'arrival': ["Monday", "Tuesday", "NA"],
        'characteristics_body_color':["red", "blue", "yellow"],
        'characteristics_body_make':["sedan", "sedan", "NA"],
        'characteristics_manuf_year':[2014, 2014, 2010]}
df = pd.DataFrame(data)

(我真的很抱歉,我不能让桌子本身看起来很明智!请不要生我的气,我是菜鸟:()

我尝试了什么

经过大量的讨论,我想出了以下解决方案:

#Import data
df_raw = pd.read_csv("sample.csv", delimiter="|")

#Parsing function
def parse_request(s):
    sj = json.loads(s)
    norm = json_normalize(sj)
    return norm

#Create an empty dataframe to store results
parsed = pd.DataFrame(columns=['id'])

#Loop through and parse JSON in each row
for i in df_raw.json_request:
    parsed = parsed.append(parse_request(i))

#Merge results back onto original dataframe
df_parsed = df_raw.join(parsed)

这显然是不优雅的,效率非常低(在我需要解析的300K行上花费多个小时)。还有更好的方法吗?

我看了

我已经完成了以下相关问题: Reading a CSV into pandas where one column is a json string (这似乎只适用于简单的,非嵌套的JSON)

JSON to pandas DataFrame (我从中借用了部分解决方案,但我无法弄清楚如何在数据帧中应用此解决方案而不循环遍历行)

我正在使用Python 3.3和Pandas 0.17。

1 个答案:

答案 0 :(得分:10)

这种方法可以将速度提高10到100倍,并且应该允许您在一分钟内读取大文件,而不是一个多小时。想法是只在读取所有数据后才构造数据帧,从而减少需要分配内存的次数,并且只对整个数据块调用json_normalize一次,而不是每次行:

import csv
import json

import pandas as pd
from pandas.io.json import json_normalize

with open('sample.csv') as fh:
    rows = csv.reader(fh, delimiter='|')
    header = next(rows)

    # "transpose" the data. `data` is now a tuple of strings
    # containing JSON, one for each row
    idents, dists, data = zip(*rows)

data = [json.loads(row) for row in data]
df = json_normalize(data)
df['ids'] = idents
df['dists'] = dists

那样:

>>> print(df)

   arrival characteristics.body.color characteristics.body.make  \
0   Monday                        red                     sedan   
1  Tuesday                       blue                     sedan   
2      NaN                     yellow                       NaN   

   characteristics.manuf_year  loc.lat  loc.lon ids  
0                        2014    45.70     38.9   1  
1                        2014    46.89     36.7   2  
2                        2010    45.70     31.0   3

此外,我查看了pandas json_normalize正在做什么,并且它正在执行一些深层副本,如果您只是从CSV创建数据帧,则不需要这些副本。我们可以实现我们自己的flatten函数,该函数使用字典并“平展”键,类似于json_normalize。然后我们可以创建一个生成器,它一次吐出一行数据帧作为记录。这种方法更快:

def flatten(dct, separator='_'):
    """A fast way to flatten a dictionary,"""
    res = {}
    queue = [('', dct)]

    while queue:
        prefix, d = queue.pop()
        for k, v in d.items():
            key = prefix + k
            if not isinstance(v, dict):
                res[key] = v
            else:
                queue.append((key + separator, v))

    return res

def records_from_json(fh):
    """Yields the records from a file object."""
    rows = csv.reader(fh, delimiter='|')
    header = next(rows)
    for ident, dist, data in rows:
        rec = flatten(json.loads(data))
        rec['id'] = ident
        rec['dist'] = dist
        yield rec

def from_records(path):
    with open(path) as fh:
        return pd.DataFrame.from_records(records_from_json(fh))

以下是计时实验的结果,我通过重复行人为地增加了样本数据的大小。行数由n_rows表示:

        method 1 (s)  method 2 (s)  original time (s)
n_rows                                               
96          0.008217      0.002971           0.362257
192         0.014484      0.004720           0.678590
384         0.027308      0.008720           1.373918
768         0.055644      0.016175           2.791400
1536        0.105730      0.030914           5.727828
3072        0.209049      0.060105          11.877403

线性推断,第一种方法应该在大约20秒内读取300k行,而第二种方法应该花费大约6秒。