การแปลงข้อมูลที่ไม่ใช่ตาราง

ETL และ ELT ด้วย Python

Jake Roach

Data Engineer

การแปลงข้อมูลที่ไม่ใช่ตาราง

ETL pipeline โดยไฮไลต์ส่วน transform

ETL และ ELT ด้วย Python

การเก็บข้อมูลใน dictionary

JSON แบบซ้อนกัน

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

เป้าหมาย:

  • แปลง dictionary ให้อยู่ในรูปแบบที่พร้อมสร้าง DataFrame

$$

[
    [863703000, 0.12187, 0.09791, 1443120000],
    [863789400, 0.09843, ...]
]
ETL และ ELT ด้วย Python

การวนซ้ำผ่านส่วนประกอบของ dictionary

# 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()

  • สร้างรายการ key ทั้งหมดใน dictionary

.values()

  • สร้างรายการ value ทั้งหมดใน dictionary

.items()

  • สร้างรายการ tuple จากคู่ key-value ทั้งหมด
ETL และ ELT ด้วย Python

การดึงข้อมูลจาก dictionary

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)
ETL และ ELT ด้วย Python

การสร้าง DataFrame จาก list of lists

ส่ง list of lists ให้ 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"]

กำหนด index ด้วย .set_index()

# Set the index column to be "timestamps"
raw_data.set_index("timestamps")
ETL และ ELT ด้วย Python

การแปลงข้อมูลหุ้น

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")
ETL และ ELT ด้วย Python

มาฝึกกันเถอะ!

ETL และ ELT ด้วย Python

Preparing Video For Download...