【问题标题】:World Bank API to pandas DF世界银行 API 到 pandas DF
【发布时间】:2023-03-26 19:56:01
【问题描述】:

我正在尝试通过 API 链接将世界银行的 API 转换为 pandas DF 格式:http://api.worldbank.org/countries/indicators/6.0.GDP_growth?per_page=100&date=2000:2015&format=json

页面响应为:

[{"page":1,"pages":147,"per_page":"2","total":294},[{"indicator":{"id":"6.0.GDP_growth","价值":"GDP 增长(年百分比)"},"country":{"id":"L5","value":"Andean Region"},"value":null,"decimal":"0","date":"2001"},{"indicator":{"id":"6.0.GDP_growth","value":"GDP 增长(年百分比)"},"country":{"id":"L5","value":"Andean Region"},"value":null,"decimal":"0","date":"2000"}]]

我正在尝试获取类似于以下内容的数据框:

Out[253]:
Country Name    GDP_growth
0   Afghanistan 14.43474129
1   Albania 1.623698601
2   Algeria 3.299991384
3   American Samoa  ..
4   Andorra -1.760010328

这是我迄今为止调用的命令:

from urllib2 import Request, urlopen
In [2]:

import json
In [3]:

from pandas.io.json import json_normalize
In [4]:

request = Request('http://api.worldbank.org/countries/indicators/6.0.GDP_growth?per_page=100&date=2000:2015&format=json')
In [5]:

response = urlopen(request)
In [6]:

elevations = response.read()

data = json.loads(elevations)

json_normalize(data['indicator'])

----------------------------------- ---------------------------- TypeError Traceback(最近一次调用 最后)在() ----> 1 json_normalize(数据['indicator'])

TypeError: 列表索引必须是整数,而不是 str

非常感谢最后一行的帮助。

谢谢!

【问题讨论】:

    标签: python json pandas


    【解决方案1】:

    data此时是一个列表。当你漂亮地打印它时,你会看到它更好:

    from pprint import pprint
    pprint(data)
    

    带有indicator 字段的第一项是data[1][0]

    【讨论】:

    • 谢谢,但您如何才能只访问国家/地区名称、GDP 增长值和年份列?
    • for item in data[1]: country = item['country']['value'], gdp_growth = item['value'], year = item['date'] # then do something with them
    • 我试过了,但它出现了错误:对于数据中的项目 [1]:国家 = 项目 ['国家']['价值'],gdp_growth = 项目 ['价值'],年份 = item['date'] country1 = pd.DataFrame(country) gdp_growth1 = pd.DataFrame(gdp_growth) year1 = pd.DataFrame(year) df_JSON = pd.DataFrame.merge(country1, gdp_growth1, year1, left_index=True, right_index= True) df_JSON = ['country', 'gdp_growth', 'year'] df_JSON.head()
    • 在这种情况下,我建议您先花时间阅读以下内容:python.org/about/gettingstartedcodecademy.com/learn/python
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2022-01-26
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多