#python #pandas
Вопрос:
import tkinter as tk
from tkinter import *
import json
import pandas as pd
import requests
import requests
url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"
headers = {
'x-rapidapi-key': "04b9735d81mshf7bd2b7070903eap1ec6f9jsnbf3d52c11b5d",
'x-rapidapi-host': "corona-virus-world-and-india-data.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers).json()
print(response)
parsed_data = json.loads(response)
print(parsed_data)
def flatten_json(json):
dict1 = {}
def flatten(i, name= dict1):
if type(i) is dict:
for a in i:
flatten(i[a], name a ‘_’)
else:
dict1[name[:-1]] = i
flatten(json)
return dict1
df = pd.DataFrame.from_dict(flatten_json(parsed_data), orient=’index’)
flatten_json(parsed_data)
Ответ №1:
# print(response)
{
"countries_stat":[
{
"country_name":"USA",
"cases":"29,920,366",
"deaths":"543,571",
...
"deaths_per_1m_population":"1,636",
"total_tests":"374,406,501",
"tests_per_1m_population":"1,126,554"
}
],
"statistic_taken_at":"2021-03-12 00:00:02",
"world_total":{
"total_cases":"119,091,428",
"new_cases":"467,990",
...
"deaths_per_1m_population":"338.8",
"statistic_taken_at":"2021-03-12 00:00:02"
}
}
# print(type(response))
<class 'dict'>
Анализируя результат, response
dict
тип is уже countries_stat
используется для преобразования в фрейм данных. Вы можете просто сделать
# The following methods all produce the same output.
df1 = pd.DataFrame(response['countries_stat'])
df2 = pd.DataFrame.from_dict(response['countries_stat'])
df3 = pd.DataFrame.from_records(response['countries_stat'])
# print(df1)
country_name cases deaths region ... total_cases_per_1m_population deaths_per_1m_population total_tests tests_per_1m_population
0 USA 29,920,366 543,571 ... 90,028 1,636 374,406,501 1,126,554
1 India 11,305,877 158,325 ... 8,137 114 224,258,293 161,409