非テーブル形式データの変換

Python で学ぶ ETL と ELT

Jake Roach

Data Engineer

非テーブル形式データの変換

変換コンポーネントを強調した ETL パイプライン

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

辞書の要素を反復処理する

# Loop over keys
for key in raw_data.keys():
    ...
# Loop over values
for value in raw_data.values():
    ...
# Loop over keys and values
for key, value in raw_data.items():
    ...

.keys()

  • 辞書に格納されたキーのリストを作成します

.values()

  • 辞書に格納された値のリストを作成します

.items()

  • キーと値のペアからなるタプルのリストを生成します
Python で学ぶ ETL と ELT

辞書からのデータ解析

entry = {
    "volume": 1443120000,
    "price": {
        "open": 0.12187,
        "close": 0.09791,
    }
}
# Parse data from dictionary using .get()
volume = entry.get("volume")
ticker = entry.get("ticker", "DCMP")
# Call .get() twice to return the nested "open" value
open_price = entry.get("price").get("open", 0)
Python で学ぶ ETL と ELT

リストのリストから DataFrame を作成する

リストのリストを pd.DataFrame() に渡します

# Pass a list of lists to pd.DataFrame
raw_data = pd.DataFrame(flattened_rows)

.columns を使って列見出しを設定します

# Create columns
raw_data.columns = ["timestamps", "open", "close", "volume"]

.set_index() を使ってインデックスを設定します

# Set the index column to be "timestamps"
raw_data.set_index("timestamps")
Python で学ぶ ETL と ELT

株価データの変換

parsed_stock_data = []

# Loop through each key-value pair of the raw_stock_data dictionary
for timestamp, ticker_info in raw_stock_data.items():
    parsed_stock_data.append([
        timestamp,
        ticker_info.get("price", {}).get("open", 0),  # Parse the opening price
        ticker_info.get("price", {}).get("close", 0),  # Parse the closing price
        ticker_info.get("volume", 0)  # Parse the volume
    ])
# Create a DataFrame, assign column names, and set an index
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...