转换 API 为 Pandas 数据帧

2024-09-30 14:31:52 发布

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

我想将API调用转换为pandasdata 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

Tags: orgapijsonhttp编辑pandasdfdata
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  

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)

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

相关问题 更多 >