用 pandas 轉換資料

使用 Python 的 ETL 與 ELT

Jake Roach

Data Engineer

在 pipeline 中轉換資料

資料需要適當轉換,才能為下游使用者提供價值

資料轉換流程。

pandas 提供強大的表格資料轉換工具

  • .loc[]
  • .to_datetime()
使用 Python 的 ETL 與 ELT

用 .loc[] 篩選記錄

.loc[] 可同時篩選並轉換 DataFrame 的兩個維度

# Keep only non-zero entries
cleaned = raw_stock_data.loc[raw_stock_data["open"] > 0, :]
# Remove excess columns
cleaned = raw_stock_data.loc[:, ["timestamps", "open", "close"]]
# Combine into one step
cleaned = raw_stock_data.loc[raw_stock_data["open"] > 0, ["timestamps", "open", "close"]]

.iloc[] 以整數索引來過濾 DataFrame

cleaned = raw_stock_data.iloc[[0:50], [0, 1, 2]]
使用 Python 的 ETL 與 ELT

變更資料型別

為符合下游情境,常需要轉換資料型別

  • .to_datetime()
# "timestamps" column currectly looks like: "20230101085731"
# Convert "timestamps" column to type datetime
cleaned["timestamps"] = pd.to_datetime(cleaned["timestamps"], format="%Y%m%d%H%M%S")
Timestamp('2023-01-01 08:57:31')
# "timestamps" column currently looks like: 1681596000011
# Convert "timestamps" column to type datatime
cleaned["timestamps"] = pd.to_datetime(cleaned["timestamps"], unit="ms")
Timestamp('2023-04-15 22:00:00.011000')
使用 Python 的 ETL 與 ELT

驗證轉換結果

資料轉換伴隨風險:

  • 資訊流失
  • 產生錯誤資料
# Several ways to investigate a DataFrame
cleaned = raw_stock_data.loc[raw_stock_data["open"] > 0, ["timestamps", "open", "close"]]
print(cleaned.head())
# Return smallest and largest records
print(cleaned.nsmallest(10, ["timestamps"]))
print(cleaned.nlargest(10, ["timestamps"]))
使用 Python 的 ETL 與 ELT

一起來練習吧!

使用 Python 的 ETL 與 ELT

Preparing Video For Download...