【问题标题】:How to split a large json file based on which time of day each entry was created?如何根据每个条目的创建时间拆分大型 json 文件?
【发布时间】:2020-03-29 20:11:47
【问题描述】:

我有一个 10GB 的 JSON 文件,我需要将它拆分为两个文件:一个包含下午 6 点到早上 6 点之间的所有条目,另一个包含早上 6 点到下午 6 点之间的所有条目。

我有以下代码使用 Pandas between_time 函数,该函数适用于较小的数据集,但内存效率非常低,以至于我的 10GB JSON 文件无法放入内存:

from pandas import read_json,to_datetime

def main():

    full_df = read_json('data.json')

    full_df['created_at'] = full_df['created_at'].astype(str).str[:-6] #strip timezone
    full_df['created_at'] = full_df['created_at'].apply(to_datetime)

    full_df = full_df.set_index('created_at')

    full_df.between_time('18:00', '6:00', True, False).reset_index().drop(columns="created_at").to_json('night.json',orient='records')
    full_df.between_time('6:00', '18:00', True, False).reset_index().drop(columns="created_at").to_json('day.json',orient='records')

if __name__ == '__main__':
    main()

这是我的数据示例:

{"field1":3253235,"field2":424444,"created_at":"2019-11-11 08:51:44.0910000 +00:00"}

有没有更简单/更有效的方法来实现这一点?

【问题讨论】:

    标签: python json pandas performance


    【解决方案1】:

    您可以像这样使用load 函数的object_hook 参数:

    def callback(obj):
        ct = obj['created_at']
        t = datetime.strptime(ct, '%Y-%m-%d %H:%M:%S')
        fname = 'night.json' if t.hour >= 18 else 'day.json'
    
        with open(fname, "a") as f:
            if f.tell() == 0:
                f.write('[')
            else:
                f.write(',')
            f.write(json.dumps(obj))
    
        return {}
    
    json.load(f, object_hook=callback)
    with open("night.json", "a") as f:
        f.write(']')
    with open("day.json", "a") as f:
        f.write(']')
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2022-01-16
      • 2017-07-23
      相关资源
      最近更新 更多