做數據處理工作時,免不了對數據中的 特殊值 進行替換。
傳統方式替換:
- 循環行、列、目標值
- 斷是否滿足條件
- 滿足條件進行替換,否則繼續
雖然思路清晰,實現起來也沒有難點,但實際工作中往往是列不同、目標值不同,替換值也不同,需要很多的循環、判斷嵌套,很容易犯編程中的 循環判斷嵌套太深、硬編碼
問題。
這種情況下,就可以藉助強大的 pandas.DataFrame.replace 來實現優雅處理。
這裏我選擇的是 dict-like (字典模式)來演示,原因如下:
- 場景全,
解決循環判斷嵌套太深問題
(後面介紹常見場景) - 調用方式相對統一,
簡單、優雅
- 可以抽象爲配置,
解決硬編碼問題
(存儲在配置文件或配置庫中)
全局替換
- 目標值相同,替換值相同
MAPPING = {
'target': 'goal'
}
df = df.replace(MAPPING)
- 目標值不同,替換值相同
MAPPING = {
'target_1': 'goal',
'target_2': 'goal'
}
df = df.replace(MAPPING)
- 目標值不同,替換值不同
MAPPING = {
'target_1': 'goal_1',
'target_2': 'goal_2'
}
df = df.replace(MAPPING)
部分列替換
- column代表列名,其它同上
MAPPING = {
'columnA': {
'target1': 'goal1'
},
'columnB': {
'target2': 'goal2'
}
}
df = df.replace(MAPPING)
正則表達式
將 MAPPING 中的 target 改爲 正則表達式字符串 或 compiled pattern ,再將 MAPPING 傳給 選填參數regex 即可。
MAPPING = {
'your_regex': 'goal'
}
df = df.replace(regex=MAPPING)