我想用Python語言將下面的鏈接轉換為Excel,這樣它就可以在Excel檔案中存盤國家和首都及其代碼的資訊。 你能指導我嗎?
https://restcountries.eu/rest/v2/alluj5u.com熱心網友回復:
Pandas庫在這里會有幫助,盡管提取你的嵌套json更多的是python的技巧。你可以按照下面的方法來簡單地提取所需的列:
Pandas庫將在這里提供幫助。
import pandas as pd
url = 'https://restcountries.eu/rest/v2/all'。
#Load json to a dataframe;
df = pd.read_json(url);
# Create DF with Country, capital and code fields. 你可以使用df.head()來查看你的資料在表格格式和列名中的樣子。
df_new = df[['name', 'capital', 'alpha2Code', 'alpha3Code']].copy()
#Use pandas ExcelWriter to write the desired DataFrame to xlsx file.
with pd.ExcelWriter('country_names.xlsx') as writer:
df_new.to_excel(writer, sheet_name=" Country List")
關于ExcelWriter模塊的全部資訊可以在https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html
中閱讀。你將需要玩一玩,改變列名和清理資料(特別是嵌套物件),這些應該只是一個搜索的程序。
uj5u.com熱心網友回復:
你最好的選擇是使用pandas從你提到的URL中讀取JSON,并將其保存到Excel檔案中。下面是它的代碼:
import pandas as pd
# Loading the JSON from the URL to a pandas dataframe[/span
df = pd.read_json('https://restcountries.eu/rest/v2/all')
# 選擇國家名稱、首都和國家代碼的列(如問題中提到的)。
df = df[["name", "capital", "alpha2Code"]]
# 將資料框保存到一個名為'restcountries.xlsx'的excel檔案中,但可以隨意更改名稱。
df.to_excel('restcountries.xlsx')
然而,在讀取嵌套欄位時將會有一個問題(如果你想在未來讀取它們)。例如,在你的資料集中名為borders和currencies的欄位是串列。因此,你可能需要在加載后進行一些后處理。
歡呼吧!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/331279.html
標籤:
上一篇:拉威爾加入計數
