비정형 데이터 변환

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...