我有一个 20GB 的
.ndjson
文件,我想用 Python 打开它。文件太大,所以我找到了一种方法,用一个在线工具将其分成 50 个文件。这是工具:https://pinetools.com/split-files
现在我得到一个文件,其扩展名为
.ndjson.000
(我不知道那是什么)
我试图将其作为 json 或 csv 文件打开,以在 pandas 中读取它,但它不起作用。 你知道如何解决这个问题吗?
import json
import pandas as pd
第一种方法:
df = pd.read_json('dump.ndjson.000', lines=True)
错误:
ValueError: Unmatched ''"' when when decoding 'string'
第二种方法:
with open('dump.ndjson.000', 'r') as f:
my_data = f.read()
print(my_data)
错误:
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 104925061 (char 104925060)
我认为问题是我的文件中有一些表情符号,所以我不知道如何对它们进行编码?
ndjson 现在支持开箱即用的参数
lines=True
import pandas as pd
df = pd.read_json('/path/to/records.ndjson', lines=True)
df.to_json('/path/to/export.ndjson', lines=True)
我认为 pandas.read_json 无法正确处理 ndjson。
根据这个问题你可以做某事。像这样阅读它。
import ujson as json
import pandas as pd
records = map(json.loads, open('/path/to/records.ndjson'))
df = pd.DataFrame.from_records(records)
P.S:此代码的所有积分均来自 Github Issue 中的 KristianHolsheimer
ndjson(换行符分隔)json是json-lines格式,即每一行都是一个json。它非常适合缺乏严格结构(“非 SQL”)的数据集,其中文件大小足以保证多个文件。
你可以使用熊猫:
import pandas as pd
data = pd.read_json('dump.ndjson.000', lines=True)
如果您的 json 字符串不包含换行符,您也可以使用:
import json
with open("dump.ndjson.000") as f:
data = [json.loads(l) for l in f.readlines()]
您始终可以逐行读取它并使用生成器遍历整个文件,而无需将其完全存储在内存中:
import json
def batch_read_ndjson(file, batch_size):
batch = []
with open(file) as f:
for line in f:
batch.append(json.load(line))
if len(batch) == batch_size:
yield batch
batch = []
batches = batch_read_ndjson("myfile.ndjson", batch_size=1000)
for batch in batches:
## do something
这样你就可以决定批量读取多少行