[英]How to use Python to extract data from the Met Office JSON download
[英]How to extract and use data from JSON in Python
我是 Python 的新手。 現在我有一個 JSON 文件。 我需要先用 Python 讀取文件,然后用它做一些事情(制作雙向表等)。 我能夠做到這一點:
import json
with open('DrateLspan.json') as f:
file = json.load(f)
for i in file:
print(i['Year'])
但是,由於我需要從 JSON 中提取數據並執行更多操作,因此我不想停留在“打印”步驟。 我試過ye = file['Year']
但它顯示“字符串索引必須是整數,而不是 str”。 誰能幫我這個? 我想使用 JSON 文件中的數據。
下面是我的 JSON 文件的前幾行:
[
{
"Year": 2015,
"Race": "All Races",
"Sex": "Both Sexes",
"Average Life Expectancy (Years)": "",
"Age-adjusted Death Rate": 733.1
},
{
"Year": 2014,
"Race": "All Races",
"Sex": "Both Sexes",
"Average Life Expectancy (Years)": 78.9,
"Age-adjusted Death Rate": 724.6
},
{
"Year": 2013,
"Race": "All Races",
"Sex": "Both Sexes",
"Average Life Expectancy (Years)": 78.8,
"Age-adjusted Death Rate": 731.9
看起來您可能對某些變量名稱有點混淆。 您正在嘗試執行以下操作:
year = file["Year"]
但是file
變量是列表而不是單個項目。 你可能的意思是:
year = i["Year"]
像這樣的事情應該可以正常工作:
import json
with open(filename) as json_file:
all_data = json.load(json_file)
for entry in all_data:
year = entry["Year"]
# Do something with year
我發現有助於避免這種混亂情況的一件事是始終將我的變量命名為特定的名稱。 希望這可以幫助!
嘗試
json 文件是字典數組。 所以您需要遍歷該列表並訪問每個 dicts 和year
屬性。 要收集所有年份,您可以將其收集到列表中。
如果你不重復,你可以使用一個set
import json
with open('test.json') as f:
data = json.load(f)
year = []
for item in data:
year.append(item['Year'])
print(year)
#uncomment the below line to remove duplicates
year = set(year)
我建議使用 Panda,它可以方便地組織您的數據。 看看它有多容易:
import json
import pandas as pd
with open('json.json') as f:
data = json.load(f)
df = pd.DataFrame.from_dict(data)
print(df)
這將創建(和打印)類似的東西:
Year Race Sex Average Life Expectancy (Years) Age-adjusted Death Rate
0 2015 All Races Both Sexes 733.1
1 2014 All Races Both Sexes 78.9 724.6
2 2013 All Races Both Sexes 78.8 731.9
然后您可以通過多種方式訪問您的數據:
print(df.loc[0,'Year'])
print(df.loc[0])
df['Year']
它非常靈活。 如果您需要快速入門,這可能是一個有價值的教程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.