【问题标题】:Read JSON file with multiple objects inside Python在 Python 中读取包含多个对象的 JSON 文件
【发布时间】:2021-03-03 19:57:57
【问题描述】:

我正在尝试在 Python 中读取 json 文件并将其转换为数据框。问题是我的 json 文件里面有几个 json 对象。我的json的结构是这样的:

{"Temp":"2,3", "OutsideTemp" : "3,4",...}
{"Temp":"3,2", "OutsideTemp" : "4,4",...}
{"Temp":"2,8", "OutsideTemp" : "3,7",...}
...

我尝试过使用 json 行和 pandas.read_json 但只有错误。 (如你所见,我是 python 的菜鸟,帮帮我!)

【问题讨论】:

    标签: python json pandas dataframe jsonlines


    【解决方案1】:

    你有一个JSON Lines格式的文本文件,所以设置lines=True

    import pandas as pd
    
    df = pd.read_json('data.txt', lines=True)
    print(df)
    

    输出

      Temp OutsideTemp
    0  2,3         3,4
    1  3,2         4,4
    2  2,8         3,7
    

    来自documentation

    lines bool,默认为 False
    将文件作为每行的 json 对象读取。

    请注意,您必须将上面 sn-p 中的data.txt 更改为您的实际文件名。

    【讨论】:

    【解决方案2】:
    import pandas as pd
    
    df = pd.read_json('data.txt', lines=True)
    df = df.apply(lambda x:x.str.replace(',','.')).astype(float)
    print(df.info())
    df
    
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 3 entries, 0 to 2
    Data columns (total 2 columns):
    Temp           3 non-null float64
    OutsideTemp    3 non-null float64
    dtypes: float64(2)
    memory usage: 176.0 bytes
    None
    

    【讨论】:

      猜你喜欢
      • 2019-01-31
      • 2018-09-22
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多