請幫我實作一個函式,該函式將按以下標準對地震資料進行分組:
光 (4.5-4.9)
中等(5-5.9)
專業(6-6.9)
強 (>=7)
我正在嘗試將此添加到我的簡單程式中,該程式從網頁收集有關地震的資料。
import json
import urllib.request
handle = urllib.request.urlopen("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson")
rawdata = handle.read()
rawdata[:400]
data = json.loads(rawdata)
data
def get_earthquake_magnitude(json_data):
results = []
for eq in json_data['features']:
mag = eq['properties']['mag']
results.append(mag)
return results
get_earthquake_magnitude(data)
uj5u.com熱心網友回復:
使用 Pandas 之類的庫可能是更好的方法。但是,如果您只想使用基本的 Python 代碼來做到這一點,這里有一種方法:
import json
import urllib.request
from collections import defaultdict
from pprint import pprint
handle = urllib.request.urlopen("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_month.geojson")
rawdata = handle.read()
data = json.loads(rawdata)
ranges = [
("Light", 5),
("Moderate", 6),
("Major", 7)]
def get_earthquake_magnitude(json_data):
groups = defaultdict(list)
for eq in json_data['features']:
mag = eq['properties']['mag']
for range in ranges:
if mag < range[1]:
groups[range[0]].append(eq)
break
else:
groups["Strong"] = eq
return groups
r = get_earthquake_magnitude(data)
for label, group in r.items():
print(f"{label}: {len(group)}")
結果:
Light: 531
Strong: 4
Moderate: 118
Major: 8
這將為您提供一個字典,其中鍵是震級的四個標簽中的每一個,值是該類別中每個地震的完整資料記錄的串列。
uj5u.com熱心網友回復:
除了上面的實作,我只是添加一個最小的例子。希望它可以有所幫助。
from collections import defaultdict
# Light (4.5-4.9)
# Moderate(5-5.9)
# Major (6-6.9)
# Strong (>=7)
# vals denoting the earthquake data
vals = [4.79, 4.58, 5.8]
mydt = {
"Light": lambda x: (x > 4.5) and (x < 4.9),
"Moderate": lambda x: (x > 5) and (x < 5.9)
}
dt = defaultdict(list)
for val in vals:
for k, v in mydt.items():
if v(val):
dt[k].append(val)
print(f"dt = {dt}")
# Output:
dt = defaultdict(<class 'list'>, {'Light': [4.79, 4.58], 'Moderate': [5.8]})
uj5u.com熱心網友回復:
pandas圖書館非常適合這樣的事情。嘗試如下:
- 用于
json_normalize創建DataFrame. - 用于
pd.cut將列中的值分箱properties.mag為離散間隔。
import pandas as pd
df = pd.json_normalize(data['features'])
bins = [0, 5, 6, 7, 100]
labels = ['Light','Moderate','Major','Strong']
df['bins'] = pd.cut(df['properties.mag'], bins=bins,
labels=labels, right=False)
讓我們檢查一下我們有多少條目用于 bin,使用df.groupby并應用于countcolumn properties.mag:
counts = df.groupby('bins')['properties.mag'].count()
print(counts)
bins
Light 531
Moderate 118
Major 8
Strong 0
Name: properties.mag, dtype: int64
使用df.describe和df.info分別獲取統計摘要和一些基本資訊df。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519937.html
標籤:Pythonjson
