【问题标题】:JSON Response into a Pandas Dataframe对 Pandas 数据框的 JSON 响应
【发布时间】:2020-05-23 16:24:57
【问题描述】:

我正在尝试将来自 https://www.loves.com/api/sitecore/StoreSearch/SearchStores 的 API 响应获取到 Pandas 数据帧中。具体来说,我正在尝试将“Points”数组加载到数据框中。我看到其他帖子表明我应该使用 json_normalize,我已经玩了一天但没有任何进展。

import json
import requests

def get(url):
    response = requests.get(url)
    parsed = json.loads(response.text)
    return json.dumps(parsed, indent=4, sort_keys=True)

from pandas.io.json import json_normalize
df = json_normalize(get(lovesLocator), 'Points')

我一直收到的错误是:

TypeError: string indices must be integers

【问题讨论】:

    标签: python json pandas dataframe python-requests


    【解决方案1】:
    import pandas as pd
    import requests
    import json
    points = json.loads(requests.get("https://www.loves.com/api/sitecore/StoreSearch/SearchStores").text)[0]["Points"]
    df = pd.DataFrame(points)
    print(df.shape) # (580, 21)
    

    【讨论】:

    • 那太好了。一个快速的问题。当我打印数据框时,我没有得到所有的键。我只看到:'Address1 Address2 AddressId AddressTypeId \'。如何在 df 中获取所有要打印的键?
    • 这只是一个显示问题。 Pandas 在打印 DataFrame 时自然会限制要显示的列数。您可以增加此限制: pd.set_option("display.max_columns", 500) pd.set_option("display.width", 1000) 更多信息,请查看this post
    猜你喜欢
    • 1970-01-01
    • 2021-09-26
    • 2021-06-17
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2014-01-05
    • 1970-01-01
    相关资源
    最近更新 更多