我正在嘗試使用此 API:https ://docs.oikolab.com/#2-1-request
他們提供了大量的檔案。我已經設法從 API 中獲取了我想要的資料,但似乎無法弄清楚如何將其轉換為 R 資料框。該頁面提供了一個示例以及如何在 Python 中轉換為 pandas 資料框,但我似乎無法在 R 中獲得相同的解決方案。
我試過 fromJSON() 但我認為由于資料的結構方式,這會導致一些問題。
這是他們在網站上給出的例子,我的問題是如何在 R 中做同樣的事情?
API 的回應如下所示:
{'attributes': {
'processing_time': 1.527,
'n_parameter_months': 851,
'gfs_reference_time': '2021-05-17 12 UTC',
'next_gfs_update': 'in 2.0 hours (approx)',
},
'data': '{"columns": ["temperature (degC)","wind_speed (m/s)"],
"index":[1262304000,1262307600,... ],
"data":[[16.59,7.61],[16.44,7.79]...]
}'
}
該網站說對于 Python 和 Pandas,轉換為這樣的資料框:
import json
import pandas as pd
weather_data = json.loads(r.json()['data'])
df = pd.DataFrame(index=pd.to_datetime(weather_data['index'],
unit='s'),
data=weather_data['data'],
columns=weather_data['columns'])
再說一遍,你將如何在 R 中復制這段代碼的結果?
謝謝!
uj5u.com熱心網友回復:
如前所述,如果您使用 來查看物件的結構,str()則可以識別要提取的元素。下面使用 json 片段(針對雙引號進行了更正):
library(jsonlite)
json_data = '{"attributes": {
"processing_time": 1.527,
"n_parameter_months": 851,
"gfs_reference_time": "2021-05-17 12 UTC",
"next_gfs_update": "in 2.0 hours (approx)"
},
"data": {"columns": ["temperature (degC)","wind_speed (m/s)"],
"index":[1262304000, 1262307600],
"data": [[16.59,7.61], [16.44,7.79]]
}
}'
weather_data_obj <- fromJSON(txt = json_data)
str(weather_data_obj)
# List of 2
# $ attributes:List of 4
# ..$ processing_time : num 1.53
# ..$ n_parameter_months: int 851
# ..$ gfs_reference_time: chr "2021-05-17 12 UTC"
# ..$ next_gfs_update : chr "in 2.0 hours (approx)"
# $ data :List of 3
# ..$ columns: chr [1:2] "temperature (degC)" "wind_speed (m/s)"
# ..$ index : int [1:2] 1262304000 1262307600
# ..$ data : num [1:2, 1:2] 16.59 16.44 7.61 7.79
data.frame然后,使用類似于 pandas的建構式構建一個資料框:
weather_data_df <- data.frame(
index = as.POSIXct(weather_data$data$index, origin = "1970-01-01"),
`colnames<-`(weather_data$data$data, weather_data$data$columns),
check.names = FALSE
)
weather_data_df
# index temperature (degC) wind_speed (m/s)
# 1 2009-12-31 18:00:00 16.59 7.61
# 2 2009-12-31 19:00:00 16.44 7.79
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412325.html
標籤:
上一篇:將json轉換為C#類
