首頁  >  文章  >  後端開發  >  用Python獲取和儲存時間序列數據

用Python獲取和儲存時間序列數據

WBOY
WBOY轉載
2023-04-11 19:30:321773瀏覽

用Python獲取和儲存時間序列數據

譯者| 布加迪

#審查學校| 孫淑娟

本教學將介紹如何使用Python從OpenWeatherMap API取得時間序列數據,並將其轉換成Pandas DataFrame。接下來,我們將使用InfluxDB Python Client,將資料寫入到時間序列資料平台InfluxDB。

我們會將來自API呼叫的JSON回應轉換成Pandas DataFrame,因為這是將資料寫入到InfluxDB的最簡單方法。由於InfluxDB是一個專門建構的資料庫,我們寫入到InfluxDB旨在滿足時間序列資料在攝取方面的高需求。

要求

本教學在透過Homebrew已安裝Python 3的macOS系統上完成。建議安裝額外的工具,例如virtualenv、pyenv或conda-env,以簡化Python和Client的安裝。完整的要求在這裡:

txt
influxdb-client=1.30.0
pandas=1.4.3
requests>=2.27.1

本教學也假設您已經建立Free Tier InfluxDB雲端帳戶或正在使用InfluxDB OSS,您也已經:

    ##建立了儲存桶。您可以將儲存桶視為資料庫或InfluxDB中最高層級的資料組織。
  • 建立了令牌。
最後,教學要求您已經使用OpenWeatherMap建立了一個帳戶,並已建立了令牌。

請求天氣資料

首先,我們需要請求資料。我們將使用請求庫,透過OpenWeatherMap API從指定的經度和緯度傳回每小時的天氣資料。

# Get time series data from OpenWeatherMap API
params = {'lat':openWeatherMap_lat, 'lon':openWeatherMap_lon, 'exclude': 
"minutely,daily", 'appid':openWeatherMap_token}
r = requests.get(openWeather_url, params = params).json()
hourly = r['hourly']

將資料轉換成Pandas DataFrame

接下來,將JSON資料轉換成Pandas DataFrame。我們也將時間戳從秒精度的Unix時間戳轉換成日期時間物件。之所以進行這種轉換,是由於InfluxDB寫入方法要求時間戳為日期時間物件格式。接下來,我們將使用這個方法,將資料寫入到InfluxDB。我們也刪除了不想寫入到InfluxDB的欄位。

python
# Convert data to Pandas DataFrame and convert timestamp to datetime 
object
df = pd.json_normalize(hourly)
df = df.drop(columns=['weather', 'pop'])
df['dt'] = pd.to_datetime(df['dt'], unit='s')
print(df.head)

將Pandas DataFrame寫入到InfluxDB

現在為InfluxDB Python客戶端程式庫建立實例,並將DataFrame寫入到InfluxDB。我們指定了測量名稱。測量含有儲存桶中的數據。您可以將其視為InfluxDB的資料組織中僅次於儲存桶的第二高層次結構。

您也可以使用data_frame__tag_columns參數指定要將哪些欄位轉換成標籤。

由於我們沒有將任何欄位指定為標籤,我們的所有欄位都會轉換成InfluxDB中的欄位。標籤用於寫入有關您的時間序列資料的元數據,可用於更有效地查詢資料子集。欄位是您在 InfluxDB中儲存實際時間序列資料的位置。該文件(https://docs.influxdata.com/influxdb/cloud/reference/key-concepts/?utm_source=vendor&utm_medium=referral&utm_campaign=2022-07_spnsr-ctn_obtaining-storing-ts-pything_tns)更詳細地介紹了InfluDBx這些數據概念。

on
# Write data to InfluxDB
with InfluxDBClient(url=url, token=token, org=org) as client:
df = df
client.write_api(write_options=SYNCHRONOUS).write(bucket=bucket,record=df,
data_frame_measurement_name="weather",
data_frame_timestamp_column="dt")

完整腳本

回顧一下,不妨看看完整的腳本。我們採取以下步驟:

1. 導入庫。

2. 收集以下內容:

    InfluxDB儲存桶
  • InfluxDB組織
  • InfluxDB令牌
  • InfluxDB URL
  • OpenWeatherMap URL
  • OpenWeatherMap 令牌
3. 建立要求。

4. 將JSON回應轉換成Pandas DataFrame。

5. 刪除您不想寫入到InfluxDB的任何欄位。

6. 將時間戳列從Unix時間轉換成Pandas日期時間物件。

7. 為InfluxDB Python Client函式庫建立實例。

8. 撰寫DataFrame,並指定測量名稱和時間戳記列。

python
import requests
import influxdb_client
import pandas as pd
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
bucket = "OpenWeather"
org = "" # or email you used to create your Free Tier 
InfluxDB Cloud account
token = " 
url = "" # for example, 
https://us-west-2-1.aws.cloud2.influxdata.com/
openWeatherMap_token = ""
openWeatherMap_lat = "33.44"
openWeatherMap_lon = "-94.04"
openWeather_url = "https://api.openweathermap.org/data/2.5/onecall"
# Get time series data from OpenWeatherMap API
params = {'lat':openWeatherMap_lat, 'lon':openWeatherMap_lon, 'exclude': 
"minutely,daily", 'appid':openWeatherMap_token}
r = requests.get(openWeather_url, params = params).json()
hourly = r['hourly']
# Convert data to Pandas DataFrame and convert timestamp to datetime 
object
df = pd.json_normalize(hourly)
df = df.drop(columns=['weather', 'pop'])
df['dt'] = pd.to_datetime(df['dt'], unit='s')
print(df.head)
# Write data to InfluxDB
with InfluxDBClient(url=url, token=token, org=org) as client:
df = df
client.write_api(write_options=SYNCHRONOUS).write(bucket=bucket,record=df,
data_frame_measurement_name="weather",
data_frame_timestamp_column="dt")

查詢資料

現在,我們已經將資料寫入到InfluxDB,可以使用InfluxDB UI來查詢資料了。導覽至資料資源管理器(從左側導覽列)。使用Query Builder(查詢建構器),選擇想要視覺化的資料和想要為之視覺化的範圍,然後點選「提交」。

用Python獲取和儲存時間序列數據

圖1. 天氣資料的預設物化視圖。 InfluxDB自動聚合時間序列數據,這樣新使用者就不會意外地查詢太多資料而導致逾時

專業提示:當您使用查詢建構器查詢資料時,InfluxDB會自動對資料進行下取樣。要查詢原始數據,請導航至Script Editor(腳本編輯器)以查看底層Flux查詢。 Flux是InfluxDB的原生查詢和腳本語言,可用於使用您的時間序列資料來分析和建立預測。使用aggregateWindow()函數取消行註解或刪除行,以查看原始資料。

用Python獲取和儲存時間序列數據

圖2. 導覽至腳本編輯器,並取消註解或刪除aggregateWindow()函數,以查看原始天氣資料

結語

但願本文能幫助您充分利用InfluxDB Python Client庫,取得時間序列資料並儲存於InfluxDB中。如果您想進一步了解使用Python Client函式庫從InfluxDB查詢數據,建議您看看這篇文章(https://thenewstack.io/getting-started-with-python-and-influxdb/)。另外值得一提的是,您可以使用Flux從OpenWeatherMap API取得數據,並將其儲存到InfluxDB。如果您使用InfluxDB Cloud,這表示該Flux腳本將被託管並定期執行,因此您可以獲得可靠的天氣資料流,並饋入到執行個體中。想進一步了解如何使用Flux依照使用者定義的時間表來取得天氣數據,請閱讀這篇文章(https://www.influxdata.com/blog/tldr-influxdb-tech-tips-handling-json-objects-mapping- arrays/?utm_source=vendor&utm_medium=referral&utm_campaign=2022-07_spnsr-ctn_obtaining-storing-ts-pything_tns)。

以上是用Python獲取和儲存時間序列數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除