我想知道是否有一种内存有效的方式将多记录 JSON 文件(每行是一个 JSON 字典)读入 pandas 数据帧。下面是一个带有工作解决方案的 2 行示例,我需要它来处理可能非常大量的记录。示例用途是处理来自 Hadoop Pig JSonStorage 函数的输出。
import json
import pandas as pd
test='''{"a":1,"b":2}
{"a":3,"b":4}'''
#df=pd.read_json(test,orient='records') doesn't work, expects []
l=[ json.loads(l) for l in test.splitlines()]
df=pd.DataFrame(l)
最佳答案
注意:read_json
现在支持行分隔的 json (从 0.19.0 开始):
In [31]: pd.read_json('{"a":1,"b":2}\n{"a":3,"b":4}', lines=True)
Out[31]:
a b
0 1 2
1 3 4
或使用文件/文件路径而不是 json 字符串:
pd.read_json(json_file, lines=True)
这将取决于数据帧的大小,哪个更快,但另一种选择是使用 str.join
粉碎你的多行“JSON”(注意:它不是有效的 json),转换成有效的 json 并使用 read_json:
In [11]: '[%s]' % ','.join(test.splitlines())
Out[11]: '[{"a":1,"b":2},{"a":3,"b":4}]'
对于这个小例子来说,这比较慢,如果在 100 左右,它是相似的,如果它更大的话, yield 会很显着......
In [21]: %timeit pd.read_json('[%s]' % ','.join(test.splitlines()))
1000 loops, best of 3: 977 µs per loop
In [22]: %timeit l=[ json.loads(l) for l in test.splitlines()]; df = pd.DataFrame(l)
1000 loops, best of 3: 282 µs per loop
In [23]: test_100 = '\n'.join([test] * 100)
In [24]: %timeit pd.read_json('[%s]' % ','.join(test_100.splitlines()))
1000 loops, best of 3: 1.25 ms per loop
In [25]: %timeit l = [json.loads(l) for l in test_100.splitlines()]; df = pd.DataFrame(l)
1000 loops, best of 3: 1.25 ms per loop
In [26]: test_1000 = '\n'.join([test] * 1000)
In [27]: %timeit l = [json.loads(l) for l in test_1000.splitlines()]; df = pd.DataFrame(l)
100 loops, best of 3: 9.78 ms per loop
In [28]: %timeit pd.read_json('[%s]' % ','.join(test_1000.splitlines()))
100 loops, best of 3: 3.36 ms per loop
注意:那个时候连接速度出奇的快。
关于python - 将多个 JSON 记录读入 Pandas 数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20037430/