Remove Currency Symbol
strip_currency · numbers · text, number
2026-09-23
กำลังประมวลผล…
strip_currency · numbers · text, number
2026-09-23
คอลัมน์เงินที่เก็บเป็น "฿1,250" เป็นข้อความ ไม่ใช่ตัวเลข การบวกหรือหาค่าเฉลี่ยจึงทำไม่ได้ เทคนิคนี้ลบสัญลักษณ์สกุลเงินที่พบบ่อยออก แล้วแปลงเป็นตัวเลขให้เลย พร้อมคงค่าที่แปลงไม่ได้ไว้เป็นข้อความเพื่อให้ไล่ตรวจต่อ
$100 กับ ฿100 — ต้องแยกสกุลเงินออกเป็นคอลัมน์ด้วย extract_pattern ก่อน ไม่อย่างนั้นตัวเลขจะเทียบกันไม่ได้฿ $ € £ ¥ ₩ ₫ และคำว่า บาท, THB, USD, EUR แบบไม่สนตัวพิมพ์toNumber เปิดอยู่ จะแปลงเป็นตัวเลข โดยเข้าใจลูกน้ำคั่นหลักพันและวงเล็บที่แปลว่าติดลบ"ไม่ระบุ" จะถูกคืนเป็นข้อความที่ลบสัญลักษณ์แล้ว ไม่กลายเป็นค่าว่างเงียบ ๆ| Parameter | Type | Default |
|---|---|---|
columns | string[] | — |
toNumber | boolean | true |
import json
import re
CURRENCY = re.compile(r'[฿$€£¥₩₫]|บาท|THB|USD|EUR', re.IGNORECASE)
def to_number(text):
negative = text.startswith('(') and text.endswith(')')
body = text[1:-1] if negative else text
body = body.replace(',', '').replace(' ', '')
if not re.fullmatch(r'[+-]?(\d+\.?\d*|\.\d+)', body):
return None
number = float(body)
return -number if negative else number
def strip_currency(value, to_number_flag=True):
if not isinstance(value, str):
return value
stripped = CURRENCY.sub('', value).strip()
if not to_number_flag:
return stripped
number = to_number(stripped)
if number is None:
return stripped
return int(number) if number == int(number) else number
values = ['฿1,250', '$ 99.50', '(2,000) บาท', 'ไม่ระบุ', None, 42]
result = [strip_currency(value) for value in values]
print(json.dumps(result, ensure_ascii=False))
คอลัมน์ price มี ฿1,250, 1250 บาท และ ไม่ระบุ ปนกัน รัน strip_currency แล้วดูใน Preview ว่ามีกี่ค่าที่ยังเป็นข้อความหลังแปลง ค่าเหล่านั้นคือรายการที่ต้องตัดสินใจต่อ เช่น เปลี่ยนเป็นค่าว่างด้วย detect_null_like หรือกรองออกด้วย filter_rows
ใช้ remove_thousand_separator เมื่อมีแค่ลูกน้ำโดยไม่มีสัญลักษณ์สกุลเงิน ใช้ convert_type เพื่อยืนยันชนิดคอลัมน์หลังทำความสะอาด และใช้ round_number เมื่อทศนิยมยาวเกินจำเป็น