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