【问题标题】:Convert API to Pandas DataFrame将 API 转换为 Pandas DataFrame
【发布时间】:2017-04-27 06:52:33
【问题描述】:
我想将 API 调用转换为 pandas data frame。
目前,API 非常杂乱无章,我想合并pandas 以使其更易于阅读/编辑/操作。
我尝试了以下方法:
r = requests.get('http://api.football-data.org/v1/competitions/398/teams')
x = r.json()
df = pd.read_json(x)
print df
但收到:
TypeError: Expected String or Unicode
【问题讨论】:
标签:
python
python-2.7
api
pandas
【解决方案1】:
read_json 函数 expects 一个字符串。您正在提供一个 JSON 对象(使用 requests 库的 json 方法解析)。您需要做的是使用json.dumps 方法将对象转换回字符串:
import json
r = requests.get('http://api.football-data.org/v1/competitions/398/teams')
x = r.json()
df = pd.read_json(json.dumps(x))
或者更好的是,直接从请求对象中获取缓冲区,不要将其转换为对象。
r = requests.get('http://api.football-data.org/v1/competitions/398/teams')
df = pd.read_json(x.text)
【解决方案2】:
pd.read_json 需要一个字符串。但是,r.json() 返回一个 dict 对象。
在您的情况下,您应该通过查看x.keys() 来探索返回的 JSON 对象的结构。这将产生['count', '_links', 'teams']。您可能对“团队”字段感兴趣。
因此,您应该执行以下操作:
r = requests.get('http://api.football-data.org/v1/competitions/398/teams')
x = r.json()
df = pd.DataFrame(x['teams'])
print df
【解决方案3】:
这个简单的解决方案对我有用(我无法访问相关的 api 链接)
df=pd.read_json('https://api.coinmarketcap.com/v1/ticker/?limit=10')
df.head()
24h_volume_usd available_supply id last_updated \
0 12465900000 16812425 bitcoin 1516379664
1 4827670000 97080757 ethereum 1516379652
2 5091970000 38739142811 ripple 1516379641
3 862348000 16920150 bitcoin-cash 1516379657
4 678044000 25927070538 cardano 1516379659
market_cap_usd max_supply name percent_change_1h \
0 198285740450 2.100000e+07 Bitcoin 0.88
1 103477408544 NaN Ethereum 0.02
2 62593157388 1.000000e+11 Ripple -0.63
3 30726992400 2.100000e+07 Bitcoin Cash 0.41
4 17206681852 4.500000e+10 Cardano 0.56
percent_change_24h percent_change_7d price_btc price_usd rank \
0 -0.37 -15.41 1.000000 11794.000000 1
1 -0.92 -15.24 0.090786 1065.890000 2
2 -1.39 -20.53 0.000138 1.615760 3
3 -2.43 -29.81 0.154675 1816.000000 4
4 -4.15 -18.47 0.000057 0.663657 5
symbol total_supply
0 BTC 16812425
1 ETH 97080757
2 XRP 99993093880
3 BCH 16920150
4 ADA 31112483745