【问题标题】:How to convert jsonreader object to Python Dataframe?如何将 jsonreader 对象转换为 Python Dataframe?
【发布时间】:2021-03-01 06:02:36
【问题描述】:

我有一个很大的 Json 文件。当我尝试如下从 Pandas 读取时,它会因内存错误而失败。


pd.read_json('http://10.10.10.10/rest/get_file.json')

所以我尝试使用块大小。现在它返回 jsonreader 对象


pd.read_json('http://10.10.10.10/rest/get_file.json', orient="records", lines=True, chunksize=50) 输出[3]:

如何将此json阅读器转换为Dataframe?

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    根据pandas文档,可以遍历Json Reader,

    
    In [262]: jsonl = '''
       .....:     {"a": 1, "b": 2}
       .....:     {"a": 3, "b": 4}
       .....: '''
       .....: 
    
    In [263]: df = pd.read_json(jsonl, lines=True)
    
    In [264]: df
    Out[264]: 
       a  b
    0  1  2
    1  3  4
    
    In [265]: df.to_json(orient='records', lines=True)
    Out[265]: '{"a":1,"b":2}\n{"a":3,"b":4}'
    
    # reader is an iterator that returns `chunksize` lines each iteration
    In [266]: reader = pd.read_json(StringIO(jsonl), lines=True, chunksize=1)
    
    In [267]: reader
    Out[267]: <pandas.io.json._json.JsonReader at 0x7f602de65520>
    
    In [268]: for chunk in reader:
       .....:     print(chunk)
       .....: 
    Empty DataFrame
    Columns: []
    Index: []
       a  b
    0  1  2
       a  b
    1  3  4
    
    

    此快照来自官方文档https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-json-reader

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 2022-07-28
      • 2015-09-15
      • 2017-01-13
      • 1970-01-01
      相关资源
      最近更新 更多