转换非表格数据

使用 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

Passons à la pratique !

使用 Python 的 ETL 和 ELT

Preparing Video For Download...