将字典列表转换为Pandas数据框
我有这段代码:
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'))
我试过这个:
import pandas as pd
df = pd.DataFrame(var)
但是我只得到了一个空的数据框。数据好像丢失了。我哪里做错了呢?
我还试过:
var = (response.read().decode('ASCII'))
这个返回的是字节字符串,我用eval()无法转换:
eval(var)
名称错误:'null' 这个名字没有定义
我不知道接下来该怎么做。
1 个回答
2
import urllib.request, 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',
}
# Prepare and make the request
req = urllib.request.Request(url, headers=hdr)
with urllib.request.urlopen(req) as response:
data = response.read().decode('utf-8') # Decode response
# Load JSON data
json_data = json.loads(data)
# Determine if the JSON data is a list or a dictionary
if isinstance(json_data, dict):
# If the JSON is a dictionary, you might want to access a particular key
# Adjust 'your_key_here' to the actual key you need, e.g., 'results'
if 'your_key_here' in json_data:
data_to_load = json_data['your_key_here']
df = pd.DataFrame(data_to_load)
else:
print("Expected key not found in JSON data")
elif isinstance(json_data, list):
# If the JSON is directly a list
df = pd.DataFrame(json_data)
else:
print("Unexpected JSON structure")
print(df.head()) # Display the first few rows to verify
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。