轉換非表格資料

使用 Python 的 ETL 與 ELT

Jake Roach

Data Engineer

轉換非表格資料

ETL 管線,已標示 transform 元件。

使用 Python 的 ETL 與 ELT

以字典儲存資料

巢狀 JSON

{
    "863703000": {
        "price": {
            "open": 0.12187,
            "close": 0.09791
        },
        "volume": 1443120000
    }, 
    "863789400": {
    }, ...
}

目標:

  • 將字典轉成可建立 DataFrame 的格式

$$

[
    [863703000, 0.12187, 0.09791, 1443120000],
    [863789400, 0.09843, ...]
]
使用 Python 的 ETL 與 ELT

走訪字典各組成

# 走訪鍵
for key in raw_data.keys():
    ...
# 走訪值
for value in raw_data.values():
    ...
# 同時走訪鍵與值
for key, value in raw_data.items():
    ...

.keys()

  • 產生字典中所有鍵的清單

.values()

  • 產生字典中所有值的清單

.items()

  • 產生鍵值對組成的 tuple 清單
使用 Python 的 ETL 與 ELT

從字典解析資料

entry = {
    "volume": 1443120000,
    "price": {
        "open": 0.12187,
        "close": 0.09791,
    }
}
# 使用 .get() 自字典解析資料
volume = entry.get("volume")
ticker = entry.get("ticker", "DCMP")
# 連續呼叫 .get() 以取得巢狀的 "open" 值
open_price = entry.get("price").get("open", 0)
使用 Python 的 ETL 與 ELT

由巢狀清單建立 DataFrame

將 list of lists 傳入 pd.DataFrame()

# 將 list of lists 傳入 pd.DataFrame
raw_data = pd.DataFrame(flattened_rows)

使用 .columns 設定欄名

# 建立欄位
raw_data.columns = ["timestamps", "open", "close", "volume"]

使用 .set_index() 設定索引

# 將索引欄設為 "timestamps"
raw_data.set_index("timestamps")
使用 Python 的 ETL 與 ELT

轉換股價資料

parsed_stock_data = []

# 逐一走訪 raw_stock_data 字典的每個鍵值對
for timestamp, ticker_info in raw_stock_data.items():
    parsed_stock_data.append([
        timestamp,
        ticker_info.get("price", {}).get("open", 0),  # 解析開盤價
        ticker_info.get("price", {}).get("close", 0),  # 解析收盤價
        ticker_info.get("volume", 0)  # 解析成交量
    ])
# 建立 DataFrame、指派欄名並設定索引
transformed_stock_data = pd.DataFrame(parsed_stock_data)
transformed_stock_data.columns = ["timestamps", "open", "close", "volume"]
transformed_stock_data = transformed_stock_data.set_index("timestamps")
使用 Python 的 ETL 與 ELT

一起來練習吧!

使用 Python 的 ETL 與 ELT

Preparing Video For Download...