【问题标题】:Read json file as pandas dataframe?将json文件读取为熊猫数据框?
【发布时间】:2018-07-14 19:30:14
【问题描述】:

我正在使用 python 3.6 并尝试使用以下代码将 json 文件(350 MB)下载为 pandas 数据框。但是,我收到以下错误:

data_json_str = "[" + ",".join(data) + "]
"TypeError: sequence item 0: expected str instance, bytes found

我该如何解决这个错误?

import pandas as pd

# read the entire file into a python array
with open('C:/Users/Alberto/nutrients.json', 'rb') as f:
   data = f.readlines()

# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)

# each element of 'data' is an individual JSON object.
# i want to convert it into an *array* of JSON objects
# which, in and of itself, is one large JSON object
# basically... add square brackets to the beginning
# and end, and have all the individual business JSON objects
# separated by a comma
data_json_str = "[" + ",".join(data) + "]"

# now, load it into pandas
data_df = pd.read_json(data_json_str)

【问题讨论】:

    标签: python json python-3.x pandas


    【解决方案1】:

    从您的代码看来,您正在加载一个 JSON 文件,该文件的每一行都包含 JSON 数据。 read_json 支持 lines 参数,如下所示:

    data_df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)
    

    注意
    如果您有单个 JSON 对象而不是每行上的单个 JSON 对象,请删除 lines=True

    【讨论】:

      【解决方案2】:

      使用 json 模块,您可以将 json 解析为 python 对象,然后从中创建一个数据框:

      import json
      import pandas as pd
      with open('C:/Users/Alberto/nutrients.json', 'r') as f:
          data = json.load(f)
      df = pd.DataFrame(data)
      

      【讨论】:

      • 我使用上面的代码得到了“JSONDecodeError: Extra data: line 2 column 1 (char 110)”
      【解决方案3】:

      如果您以二进制文件 ('rb') 打开文件,您将获得字节。怎么样:

      with open('C:/Users/Alberto/nutrients.json', 'rU') as f:
      

      也如this 回答中所述,您也可以直接使用熊猫:

      df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)
      

      【讨论】:

        【解决方案4】:

        如果你想把它转换成 JSON 对象的 array,我想这个会做你想做的

        import json
        data = []
        with open('nutrients.json', errors='ignore') as f:
            for line in f:
                data.append(json.loads(line))
        print(data[0])
        

        【讨论】:

          【解决方案5】:

          使用 pandas 读取 json 文件最简单的方法是:

          pd.read_json("sample.json",lines=True,orient='columns')
          

          像这样处理嵌套的json

          [[{Value1:1},{value2:2}],[{value3:3},{value4:4}],.....]

          使用 Python 基础知识

          value1 = df['column_name'][0][0].get(Value1)
          

          【讨论】:

          • 这里的 Value1 是什么?列名?
          • @Kubra Value1 为key,会返回对应的值。
          【解决方案6】:

          请输入下面的代码

          #call the pandas library
          import pandas as pd
          #set the file location as URL or filepath of the json file
          url = 'https://www.something.com/data.json'
          #load the json data from the file to a pandas dataframe
          df = pd.read_json(url, orient='columns')
          #display the top 10 rows from the dataframe (this is to test only)
          df.head(10)
          

          请查看代码并根据您的需要进行修改。我添加了 cmets 来解释每一行代码。希望这会有所帮助!

          【讨论】:

            猜你喜欢
            • 2021-11-11
            • 1970-01-01
            • 2016-12-25
            • 2013-07-23
            • 2019-03-31
            • 2020-04-05
            • 2019-07-28
            • 2021-08-21
            相关资源
            最近更新 更多