使用 pandas 转换数据

Python 中的 ETL 与 ELT

Jake Roach

Data Engineer

在流水线中转换数据

必须正确转换数据,才能为下游用户提供价值

数据转换工作流。

pandas 提供强大的表格数据转换工具

  • .loc[]
  • .to_datetime()
Python 中的 ETL 与 ELT

用 .loc[] 筛选记录

.loc[] 可同时转换 DataFrame 的两维

# 仅保留非零行
cleaned = raw_stock_data.loc[raw_stock_data["open"] > 0, :]
# 移除多余列
cleaned = raw_stock_data.loc[:, ["timestamps", "open", "close"]]
# 合并为一步
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" 列当前类似:"20230101085731"
# 将 "timestamps" 列转换为 datetime 类型
cleaned["timestamps"] = pd.to_datetime(cleaned["timestamps"], format="%Y%m%d%H%M%S")
Timestamp('2023-01-01 08:57:31')
# "timestamps" 列当前类似:1681596000011
# 将 "timestamps" 列转换为 datetime 类型
cleaned["timestamps"] = pd.to_datetime(cleaned["timestamps"], unit="ms")
Timestamp('2023-04-15 22:00:00.011000')
Python 中的 ETL 与 ELT

验证转换结果

数据转换存在风险:

  • 信息丢失
  • 生成错误数据
# 调查 DataFrame 的多种方式
cleaned = raw_stock_data.loc[raw_stock_data["open"] > 0, ["timestamps", "open", "close"]]
print(cleaned.head())
# 返回最小与最大记录
print(cleaned.nsmallest(10, ["timestamps"]))
print(cleaned.nlargest(10, ["timestamps"]))
Python 中的 ETL 与 ELT

让我们一起练习吧!

Python 中的 ETL 与 ELT

Preparing Video For Download...