PyGrayJSON如何将数据解析到Python笔记本上的Pandas

2024-09-30 22:10:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在Jupyter笔记本中构建的python脚本,用于查询我自己的Instagram句柄,但我似乎无法将所有数据放入pandas数据框,有人能帮我吗?

    from instagram.client import InstagramAPI    
    import pandas as pd    
    import requests  
    import json   

    access_token = "xxxx"  
    client_secret = "xxxx"  

    recentMediaResponse = requests.get("https://api.instagram.com/v1/users/self/media/recent/",params = {"access_token": access_token})
    recentMediaJson = json.loads(recentMediaResponse.text)     

    DataDF = pd.DataFrame(columns = ['numComments', 'likes', 'id', 'tags'])

    numcomments = pd.DataFrame({'numComments' : [recentMediaJson['data'][1]['comments']['count']],
                               'likes': [recentMediaJson['data'][1]['likes']['count']],
                               'id': [recentMediaJson['data'][1]['id']],
                               'tags': [recentMediaJson['data'][1]['tags']]


                               })
    Final = DataDF.append(numcomments)
    print Final

当我打印'Final'变量时,我只得到一个id和所有相应的数据值/字符串:

enter image description here

我知道有很多数据,因为“recentMediaJson”文件就是这样的:enter image description here


Tags: 数据importclienttokenidpandasdataaccess
2条回答

在本节中,我认为您正在选择字典列表中的第一个元素recentMediaJson['data'][1]。您需要遍历列表中的所有条目,并每次将numcomments追加到DataDF。在

numcomments = pd.DataFrame({'numComments' : [recentMediaJson['data'][1]['comments']['count']],
                                   'likes': [recentMediaJson['data'][1]['likes']['count']],
                                   'id': [recentMediaJson['data'][1]['id']],
                                   'tags': [recentMediaJson['data'][1]['tags']]

此外,您还可以使用pprint直观地显示api返回的json对象。尝试导入pprint并运行pprint.pprint(recentMediaJson),您将能够更好地看到结构。在

您只包含来自JSON数据的一条记录。在

我从这里得到了答案:JSON to pandas DataFrame

这是未经测试的,但这样的东西应该行得通。在

data = json.loads(recentMediaResponse.text)
numComments,likes,id,tags = [],[],[],[]
for result in data['results']:
    numcomments.append(result['comments']['count'])
    likes.append(result['likes']['count'])
    id.append(result['id'])
    tags.append(result['tags'])
df = pd.DataFrame([numcomments,likes,id,tags]).T
print df

相关问题 更多 >