紀錄一下如何在 Data Integration pipeline 中,使用 Transform 轉換欄位名稱。
例如這是我原始 Table
| UU01 | UU02 | UU03 |
|---|---|---|
| 51982064-26f7-435c-a935-bf522ebda29d | 王曉明 | 1 |
| 91d49f51-495d-4d98-833e-a1e090475195 | 張阿榮 | 0 |
| 251e5455-c061-4836-b2d7-ee40b7da4f54 | 陳曉嵐 | 1 |
| 0295db65-b2e3-40ac-b2ec-24798703df1b | 陳大華 | 2 |
而我想轉成:
| id | name | status |
|---|---|---|
| 51982064-26f7-435c-a935-bf522ebda29d | 王曉明 | 1 |
| 91d49f51-495d-4d98-833e-a1e090475195 | 張阿榮 | 0 |
| 251e5455-c061-4836-b2d7-ee40b7da4f54 | 陳曉嵐 | 1 |
| 0295db65-b2e3-40ac-b2ec-24798703df1b | 陳大華 | 2 |
Transform
要進行以下修改,要使用 transform
code 如下
from mage_ai.data_cleaner.transformer_actions.base import BaseAction
from mage_ai.data_cleaner.transformer_actions.constants import ActionType, Axis
from mage_ai.data_cleaner.transformer_actions.utils import build_transformer_action
from pandas import DataFrame
if 'transformer' not in globals():
from mage_ai.data_preparation.decorators import transformer
if 'test' not in globals():
from mage_ai.data_preparation.decorators import test
@transformer
def transform(df: DataFrame, *args, **kwargs) -> DataFrame:
"""
欄位轉換,這段程式會根據 mapping 變數的 key / value 轉換匯出的欄位
"""
mapping = {
"UU01": "id",
"UU02": "name",
"UU03": "status"
}
# 實際執行 rename;不存在的欄位會被忽略
df_renamed = df.rename(columns=mapping)
return df_renamed
@test
def test_output(output, *args) -> None:
"""
Template code for testing the output of the block.
"""
assert output is not None, 'The output is undefined'
執行完畢後,就會匯出欄位名稱是 id / name / status
沒有留言:
張貼留言