【问题标题】:How do I convert a large JSON file to a Pandas Dataframe or a regular CSV file?如何将大型 JSON 文件转换为 Pandas Dataframe 或常规 CSV 文件?
【发布时间】:2018-04-29 09:32:02
【问题描述】:

我已经尝试过 json_normalize,这似乎可行;但是,它不会打印我想要的输出。

import requests
import json
from pandas.io.json import json_normalize
import pandas as pd

url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"

aResponse = requests.get(url)



y = json.loads(aResponse.content)
json_test = json.dumps(y, indent = 4, sort_keys=True)
print(json_test)
csv = json_normalize(y['results'])
print(csv)

显示这段代码的输出很困难,而且非常混乱;因此,我认为我将其排除在外符合我们双方的最大利益。如果这是一条有用的信息,我可以添加它。

json.dumps 部分只是组织了我的 json 文件,以便于查看。不幸的是,我不能发布整个 json 文件,因为 Stack 不是我的格式的忠实粉丝。这是一个小sn-p:

{
"query_parameters": {
    "limit": 10,
    "mID": "54a309ae1c61be23aba0da62",
    "skip": 0,
    "sort": 1
},
"results": [
    {
        "cID": "5314ab42d34b6c5b402aead4",
        "content": "BE9kUwvLfsAmI",
        "content_data": {
            "added_with_admin": false,
            "dateAdded": 1393863490.072894,
            "embedLink": "http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif",
            "still_image": "http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif",
            "tags": [
                "adam levine",
                "embarassed",
                "the voice",
                "confession"
            ]
        },
        "content_type": "gif",
        "index": 269,
        "parameters": {
            "mu": 35.92818823777915,
            "sigma": 1.88084276812386
        },
        "rank": 0
    },

其中大约还有 10 个(范围一直到 6119;但是,我正在尝试仅完成其中的一部分)。我希望我的输出按如下顺序排列:rank、tags、embedLink、mu、sigma、index。这是我想要的输出示例:

0, adam levine, embarassed, the voice, confession, http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif, 35.92818823777915, 1.88084276812386, 269

我想把它作为一个 csv 文件;但是,我认为使用 Pandas 创建数据框也很有用。我认为我的问题出现是因为我有这么大的嵌入式 json 文件,并且计算机很难组织这个大数据集。任何意见,将不胜感激!

【问题讨论】:

    标签: python json pandas csv python-requests


    【解决方案1】:

    首先,您可以使用requests.json() 代替requests.text 来获取JSON 格式的响应内容。

    import requests
    import pandas as pd
    from pprint import pprint
    
    url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"
    
    response = requests.get(url)
    results = response.json()["results"]
    
    # pprint(results)
    
    [{'cID': '5314ab42d34b6c5b402aead4',
      'content': 'BE9kUwvLfsAmI',
      'content_data': {'added_with_admin': False,
                       'dateAdded': 1393863490.072894,
                       'embedLink': 'http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif',
                       'still_image': 'http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif',
                       'tags': ['adam levine',
                                'embarassed',
                                'the voice',
                                'confession']},
      'content_type': 'gif',
      'index': 269,
      'parameters': {'mu': 35.92818823777915, 'sigma': 1.88084276812386},
      'rank': 0},
     {'cID': '5314ab4dd34b6c5b402aeb97',
      ...
    

    然后你可以用pd.DataFrame.from_dict加载字典:

    df = pd.DataFrame.from_dict(results)
    
    # print(df.head(2))
    
                            cID        content  \
    0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI   
    1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2   
    
                                            content_data content_type  index  \
    0  {'embedLink': 'http://media3.giphy.com/media/B...          gif    269   
    1  {'embedLink': 'http://media1.giphy.com/media/N...          gif    464   
    
                                              parameters  rank  
    0  {'mu': 35.92818823777915, 'sigma': 1.880842768...     0  
    1  {'mu': 35.70238333972232, 'sigma': 1.568292935...     1  
    

    然后使用.apply(pd.Series)进一步扩展dict中的列:

    df = pd.concat([df.drop(["content_data"], axis=1), df["content_data"].apply(pd.Series)], axis=1)
    df = pd.concat([df.drop(["parameters"], axis=1), df["parameters"].apply(pd.Series)], axis=1)
    
    # print(df.head(2))
                            cID        content content_type  index  rank  \
    0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI          gif    269     0   
    1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2          gif    464     1   
    
       added_with_admin     dateAdded  \
    0             False  1.393863e+09   
    1             False  1.393864e+09   
    
                                               embedLink  \
    0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...   
    1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...   
    
                                             still_image  \
    0  http://media.giphy.com/media/BE9kUwvLfsAmI/200...   
    1  http://media.giphy.com/media/NZhO1SEuFmhj2/200...   
    
                                                    tags         mu     sigma  
    0   [adam levine, embarassed, the voice, confession]  35.928188  1.880843  
    1  [ryan gosling, facepalm, embarrassed, confession]  35.702383  1.568293
    

    并将标签从列表转换为字符串:

    df["tags"] = df["tags"].apply(lambda x: ", ".join(x))
    
    # print(df.head(2)["tags"])
    
    0     adam levine, embarassed, the voice, confession
    1    ryan gosling, facepalm, embarrassed, confession
    

    最后得到你想要的列:

    df = df[["rank", "tags", "embedLink", "mu", "sigma", "index"]]
    
    # print(df.head(2))
    
       rank                                             tags  \
    0     0   adam levine, embarassed, the voice, confession   
    1     1  ryan gosling, facepalm, embarrassed, confession   
    
                                               embedLink         mu     sigma  \
    0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...  35.928188  1.880843   
    1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...  35.702383  1.568293   
    
       index  
    0    269  
    1    464
    

    【讨论】:

    • 我一定会试一试的!不过这看起来很棒,非常感谢!
    • @P.Nar 希望这会有所帮助!
    • 有没有办法将此数据添加到excel文件中?
    • @P.Nar 你可以使用pandas.DataFrame.to_excelwriter = pd.ExcelWriter('output.xlsx'); df.to_excel(writer,'Sheet1'); writer.save()
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2017-01-29
    • 1970-01-01
    • 2012-06-17
    相关资源
    最近更新 更多