紀錄一下如何在 Data Integration pipeline 中,使用 Transform 轉換欄位值。
例如現在我有 Table 紀錄員工狀態(1:在職;0:離職;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 |
想讓匯出的 table 的 status 變成「在職/離職/留職停薪」
欄位修改
首先匯入的 table 要修改
原本是
| Name | Type | Unique | Bookmark | Key prop |
|---|---|---|---|---|
| id | string | |||
| status | number |
要改成
| Name | Type | Unique | Bookmark | Key prop |
|---|---|---|---|---|
| id | string | |||
| status | string ↑ status改成 string 類型 |
Transform
還要建立 Transform 如下:
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
import pandas as pd
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(data: DataFrame, *args, **kwargs) -> DataFrame:
"""
修改 status 欄位
"""
status_num = pd.to_numeric(data['status'], errors='coerce')
data['status'] = status_num.map({
1: '在職',
0: '離職',
2: '留職停薪'
}).fillna('未知') # 如果有例外狀況,通通顯示未知
# 以上的程式是直接取代 status 欄位
# 如果要保留 status 數字,新增不同欄位的填入「在職/離職/留職停薪」,
# 則改成如下這樣即可
# data['status_name'] = status_num.map({ ... 中略 })
return data
@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 |
|---|---|---|
| 51982064-26f7-435c-a935-bf522ebda29d | 王曉明 | 在職 |
| 91d49f51-495d-4d98-833e-a1e090475195 | 張阿榮 | 離職 |
| 251e5455-c061-4836-b2d7-ee40b7da4f54 | 陳曉嵐 | 在職 |
| 0295db65-b2e3-40ac-b2ec-24798703df1b | 陳大華 | 留職停薪 |
沒有留言:
張貼留言