将字典列表转换为Pandas DataFrame时遇数据丢失等问题求助
问题:调用WTO API获取数据后无法转换为Pandas DataFrame
我编写了调用WTO API获取数据的Python代码:
import urllib.request, json url = "https://api.wto.org/timeseries/v1/indicator_categories?lang=1" hdr ={ # Request headers 'Cache-Control': 'no-cache', 'Ocp-Apim-Subscription-Key': '21cda66d75fc4010b8b4d889f4af6ccd', } req = urllib.request.Request(url, headers=hdr) req.get_method = lambda: 'GET' response = urllib.request.urlopen(req) #print(response.getcode()) var = print(response.read().decode('ASCII'))
尝试用以下代码转换为Pandas DataFrame时,得到空DataFrame:
import pandas as pd df = pd.DataFrame(var)
之后我修改为直接赋值解码后的字符串:
var = (response.read().decode('ASCII'))
但用eval(var)解析时出现错误:
eval(var)
NameError: name 'null' is not defined
解决方案
错误1:用print()赋值变量
print()函数的返回值是None,所以你把print()的结果赋值给var时,var实际是None,用pd.DataFrame(None)自然得到空DataFrame。正确做法是直接将解码后的响应内容赋值给变量,不要嵌套print():
# 错误写法 var = print(response.read().decode('ASCII')) # 正确写法 response_str = response.read().decode('ASCII')
错误2:用eval()解析JSON字符串
JSON格式中的null、true、false和Python的None、True、False语法不兼容,eval()无法识别这些JSON关键字。应该用Python内置的json模块来解析JSON字符串,它会自动处理这些格式差异:
data = json.loads(response_str)
完整正确代码
import urllib.request import json import pandas as pd url = "https://api.wto.org/timeseries/v1/indicator_categories?lang=1" hdr = { 'Cache-Control': 'no-cache', 'Ocp-Apim-Subscription-Key': '21cda66d75fc4010b8b4d889f4af6ccd', } req = urllib.request.Request(url, headers=hdr) response = urllib.request.urlopen(req) # 读取并解码响应 response_str = response.read().decode('ASCII') # 解析JSON为Python数据结构 data = json.loads(response_str) # 转换为Pandas DataFrame df = pd.DataFrame(data) print(df)
这段代码会正确解析API返回的JSON数据,并转换为有效的DataFrame。
内容的提问来源于stack exchange,提问作者prashanth manohar
相关产品推荐
相关产品推荐

