【问题标题】:Fast Parsing a huge 12 GB JSON file with Python使用 Python 快速解析 12 GB 的巨大 JSON 文件
【发布时间】:2020-10-19 00:43:24
【问题描述】:

我有一个 12GB 的 JSON 文件,其中每一行都包含有关科学论文的信息。看起来是这样的

enter image description here

我想解析它并创建 3 个 pandas 数据框,其中包含有关场所、作者以及作者在某个场所发表过多少次的信息。下面你可以看到我写的代码。我的问题是这段代码需要很多天才能运行。有没有办法让它更快?

venues = pd.DataFrame(columns = ['id', 'raw', 'type'])
authors = pd.DataFrame(columns = ['id','name'])
main = pd.DataFrame(columns = ['author_id','venue_id','number_of_times'])
with open(r'C:\Users\dintz\Documents\test.json',encoding='UTF-8') as infile:
    papers = ijson.items(infile, 'item')
    for paper in papers:
        if 'id' not in paper["venue"]:
            if 'type' not in paper["venue"]:
                venues = venues.append({'raw': paper["venue"]["raw"]},ignore_index=True)
            else:
                venues = venues.append({'raw': paper["venue"]["raw"], 'type': paper["venue"]["type"]},ignore_index=True)
        else:
            venues = venues.append({'id': paper["venue"]["id"] , 'raw': paper["venue"]["raw"], 'type': paper["venue"]["type"]},ignore_index=True)
        paper_authors = paper["authors"]
        paper_authors_json = json.dumps(paper_authors)
        obj = ijson.items(paper_authors_json,'item')
        for author in obj:
            authors = authors.append({'id': author["id"] , 'name': author["name"]},ignore_index=True)
            main = main.append({'author_id': author["id"] , 'venue_raw': venues.iloc[-1]['raw'],'number_of_times': 1},ignore_index=True)

authors = authors.drop_duplicates(subset=None, keep='first', inplace=False)
venues = venues.drop_duplicates(subset=None, keep='first', inplace=False)
main = main.groupby(by=['author_id','venue_raw'], axis=0, as_index = False).sum()

【问题讨论】:

    标签: python json python-3.x


    【解决方案1】:

    Apache Spark 允许并行读取多个块中的 json 文件以使其更快 - https://spark.apache.org/docs/latest/sql-data-sources-json.html

    对于常规的多行 JSON 文件,将 multiLine 参数设置为 True。

    如果你不熟悉 Spark,你可以在 Spark 上使用 Pandas 兼容层,称为 Koalas -

    https://koalas.readthedocs.io/en/latest/

    考拉 read_json 调用 - https://koalas.readthedocs.io/en/latest/reference/api/databricks.koalas.read_json.html

    【讨论】:

      【解决方案2】:

      您使用错误的工具来完成此任务,请勿在此场景中使用 pandas。 再看最后3行代码,简洁干净,但是在不能使用read_json()或read_csv()等pandas输入函数的情况下,如何将这些数据填充到pandas dataframe中就不是那么容易了。

      我更喜欢使用纯python来完成这个简单的任务,如果你的电脑有足够的内存,使用dict获取唯一的作者和场地,使用itertools.groupby进行分组并使用more_itertools.ilen计算计数。

      authors = {}
      venues = {}
      for paper in papers:
          venues[paper["venue"]["id"]] = (paper["venue"]["raw"], paper["venue"]["type"])
      for author in obj:
          authors[author["id"]] = author["name"]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 2015-06-28
        • 2018-12-09
        • 1970-01-01
        • 2014-10-14
        相关资源
        最近更新 更多