我需要從 API 獲取資料,然后轉換為 pandas 資料框。到目前為止,我能夠使用 for 回圈來實作這一點(當我有一個資料集時這很有效)。現在我有幾個資料框,我想知道如何撰寫一個從 API 中提取資料并構建資料框的函式。
示例代碼:
motion_fourth = ['sensor1_id', 'sensor2_id', 'sensor3_id']
motion_fifth = ['sensor4_id', 'sensor5_id', 'sensor6_id']
motion_results_fourth = []
motion_results_fifth = []
# Iterate get urls and retrieve json files
for sensor in motion_sensors_fourth:
res = requests.get(f'https://apiv2.XXXX/sensors/{sensor}/Event/history?tstart={timestamp1}&tend={timestamp2}', headers=headers)
if res.status_code == 200:
motion_results_fourth.append(res.json())
else:
print(f'Request to {sensor} failed.')
# Create motion dataframes
sensor1_motion = pd.DataFrame(motion_results_fourth[0])
sensor2_motion = pd.DataFrame(motion_results_fourth[1])
sensor3_motion = pd.DataFrame(motion_results_fourth[2])
然后在完成這個for回圈并轉換為資料幀之后,我需要再次為motion_fifth重復它......所以我的問題是如何定義一個檢索API資料的函式,將幾個傳感器ID串列放入資料幀中(又名motion_fourth、motion_fifth等)
uj5u.com熱心網友回復:
我建議您創建一個接收通用串列作為引數的函式。所以你可以為第四和第五運行相同的功能。
有點像這樣:
def create_motion_df(motion_sensor_list)
# Iterate get urls and retrieve json files
for sensor in motion_sensor_list:
res = requests.get(f'https://apiv2.XXXX/sensors/{sensor}/Event/history?tstart={timestamp1}&tend={timestamp2}', headers=headers)
if res.status_code == 200:
motion_sensor_list.append(res.json())
else:
print(f'Request to {sensor} failed.')
sensor1_motion = pd.DataFrame(motion_sensor_list[0])
sensor2_motion = pd.DataFrame(motion_sensor_list[1])
sensor3_motion = pd.DataFrame(motion_sensor_list[2])
return sensor1_motion, sensor2_motion, sensor3_motion
uj5u.com熱心網友回復:
也許您可以嘗試將資料存盤在字典中。
在下面的示例中,我為每個動作的傳感器串列創建了一個字典。還有一本字典,我們可以在其中存盤每個動作的字典。在該嵌套字典中,您將結果鏈接到傳感器。
我沒有測驗過,但也許你可以試試。
motions = {'fourth':['sensor1_id', 'sensor2_id', 'sensor3_id'],
'fifth' = ['sensor4_id', 'sensor5_id', 'sensor6_id']}
motion_results = {'fourth':{},'fifth':{}}
for motion, sensors in motions.values():
for sensor in sensors:
res = requests.get(f'https://apiv2.XXXX/sensors/{sensor}/Event/history?tstart={timestamp1}&tend={timestamp2}', headers=headers)
if res.status_code == 200:
motion_results[motion][sensor] = res.json()
else:
print(f'Request to {motion} - {sensor} failed.')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424460.html
上一篇:如何匹配值?
