【发布时间】:2018-06-05 12:45:27
【问题描述】:
我正在处理一个每行包含一个 json 块的文件。每行看起来像这样:
{"a":3,"b":10,"unnecessaryList":[{"value":12,"colName":"c"},{"value":792,"colName":"d"},{"value":645,"colName":"e"}],"index":"-1417561653"}
json 的生产者选择了不必要的嵌套结构,而平面结构就足够了。也就是说,我想以更明显的扁平结构将数据读入 Pandas DataFrame,其中包含“a”、“b”、“c”、“d”、“e”、“index”列。到目前为止,我想出的最好方法是以不同的方式处理文件两次:
import pandas as pd
from pandas.io.json import json_normalize, loads
raw_json = pd.read_json('sample.json', lines=True)
raw_json.set_index('index', inplace=True)
with open('sample.json') as f:
lines = f.readlines()
exploded_columns = pd.concat([json_normalize(loads(l), 'unnecessaryList', 'index').pivot(index='index', columns='colName', values='value') for l in lines])
data = pd.merge(raw_json[['a', 'b']], exploded_columns, left_index=True, right_index=True)
有没有办法避免像这样两次读取数据? Pandas 是否提供了一些可以避免我提出的 concat/normalize/pivot/merge 垃圾的功能?
【问题讨论】: