การแปลงข้อมูลด้วย pandas

ETL และ ELT ด้วย Python

Jake Roach

Data Engineer

การแปลงข้อมูลใน pipeline

ข้อมูลต้องได้รับการแปลงอย่างเหมาะสมเพื่อให้เป็นประโยชน์ต่อผู้ใช้ปลายทาง

เวิร์กโฟลว์การแปลงข้อมูล

pandas มีเครื่องมือทรงพลังสำหรับแปลงข้อมูลแบบตาราง

  • .loc[]
  • .to_datetime()
ETL และ ELT ด้วย Python

การกรองข้อมูลด้วย .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]]
ETL และ ELT ด้วย Python

การเปลี่ยนชนิดข้อมูล

ชนิดข้อมูลมักต้องแปลงให้เหมาะกับการใช้งานปลายทาง

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

การตรวจสอบผลการแปลงข้อมูล

การแปลงข้อมูลมีความเสี่ยงที่ต้องระวัง:

  • การสูญเสียข้อมูล
  • การสร้างข้อมูลที่ผิดพลาด
# 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"]))
ETL และ ELT ด้วย Python

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

ETL และ ELT ด้วย Python

Preparing Video For Download...