Read json file as pandas dataframe?

前端 未结 5 1901
夕颜
夕颜 2020-12-15 06:14

I am using python 3.6 and trying to download json file (350 MB) as pandas dataframe using the code below. However, I get the following error:

da         


        
相关标签:
5条回答
  • 2020-12-15 06:45

    Please the code below

    #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)
    

    Please review the code and modify based on your need. I have added comments to explain each line of code. Hope this helps!

    0 讨论(0)
  • 2020-12-15 06:46

    From your code, it looks like you're loading a JSON file which has JSON data on each separate line. read_json supports a lines argument for data like this:

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

    Note
    Remove lines=True if you have a single JSON object instead of individual JSON objects on each line.

    0 讨论(0)
  • 2020-12-15 06:57

    If you open the file as binary ('rb'), you will get bytes. How about:

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

    Also as noted in this answer you can also use pandas directly like:

    df = pd.read_json('C:/Users/Alberto/nutrients.json', lines=True)
    
    0 讨论(0)
  • 2020-12-15 07:00

    Using the json module you can parse the json into a python object, then create a dataframe from that:

    import json
    import pandas as pd
    with open('C:/Users/Alberto/nutrients.json', 'r') as f:
        data = json.load(f)
    df = pd.DataFrame(data)
    
    0 讨论(0)
  • 2020-12-15 07:02

    if you want to convert it into an array of JSON objects, I think this one will do what you want

    import json
    data = []
    with open('nutrients.json', errors='ignore') as f:
        for line in f:
            data.append(json.loads(line))
    print(data[0])
    
    0 讨论(0)
提交回复
热议问题