Convert Type
convert_type · types · any
2026-09-23
กำลังประมวลผล…
convert_type · types · any
2026-09-23
ไฟล์ CSV ไม่มีชนิดข้อมูล ทุกอย่างมาเป็นข้อความ ตราบใดที่คอลัมน์ยอดขายยังเป็น text การหาค่าเฉลี่ยหรือเรียงลำดับจะให้ผลผิด เทคนิคนี้เปลี่ยนชนิดให้ชัดเจน และบังคับให้คุณตัดสินใจว่าจะทำอย่างไรกับค่าที่แปลงไม่ได้ แทนที่จะปล่อยให้เงียบหาย
round_number01000 หรือเบอร์โทร 0812345678 — การแปลงเป็นตัวเลขทำให้ศูนย์หายอย่างถาวร ให้คงเป็น textsplit_column หรือ extract_patterntointeger และ decimal รองรับรูปแบบที่พบจริง — สัญลักษณ์สกุลเงิน เครื่องหมายคั่นหลักพัน วงเล็บที่แปลว่าติดลบ และเปอร์เซ็นต์ โดย integer จะตัดเศษทิ้ง ไม่ปัดboolean รับ yes/no, true/false, 1/0 และ ใช่/ไม่ใช่date อ่านเฉพาะรูปแบบที่ไม่กำกวม ถ้ากำกวมให้ใช้ normalize_date ซึ่งถามคุณก่อนonError — null เปลี่ยนเป็นค่าว่าง ส่วน keep เก็บข้อความเดิมไว้ให้ไล่ตรวจต่อ พร้อมรายงานจำนวนใน Preview เสมอ| Parameter | Type | Default |
|---|---|---|
columns | string[] | — |
to | text | integer | decimal | boolean | date | "text" |
onError | null | keep | "null" |
import json
import math
import re
CURRENCY = re.compile(r'[฿$€£¥₩₫]|บาท|THB|USD|EUR', re.IGNORECASE)
def parse_number_like(value):
if isinstance(value, bool):
return 1 if value else 0
if isinstance(value, (int, float)):
return value
if not isinstance(value, str):
return None
text = CURRENCY.sub('', value).strip()
is_percent = text.endswith('%')
if is_percent:
text = text[:-1].strip()
negative = text.startswith('(') and text.endswith(')')
if negative:
text = text[1:-1]
text = text.replace(',', '').replace(' ', '')
if not re.fullmatch(r'[+-]?(\d+\.?\d*|\.\d+)', text):
return None
number = float(text)
if negative:
number = -number
return number / 100 if is_percent else number
def convert_type(value, to='text', on_error='null'):
if value is None:
return None
if to == 'text':
return str(value)
number = parse_number_like(value)
converted = None if number is None else (math.trunc(number) if to == 'integer' else number)
if converted is None and on_error == 'keep':
return value
return converted
values = ['12', '฿1,250.50', '(300)', '15%', 'ไม่ระบุ', None, True]
result = [convert_type(value, 'integer') for value in values]
print(json.dumps(result, ensure_ascii=False))
คอลัมน์ amount ถูกอ่านเป็น text เพราะมี ฿ และลูกน้ำ เลือก to เป็น decimal และ onError เป็น keep ในรอบแรก เพื่อดูใน Preview ว่ามีกี่ค่าที่แปลงไม่ได้และหน้าตาเป็นอย่างไร เมื่อจัดการค่าประหลาดครบแล้ว ค่อยเปลี่ยน onError เป็น null เพื่อให้คอลัมน์เป็นตัวเลขล้วน
ใช้ detect_type เมื่ออยากให้ระบบเสนอชนิดที่เหมาะสมให้ก่อน ใช้ strip_currency เมื่ออยากเห็นขั้นตอนการลบสัญลักษณ์แยกชัดใน Pipeline และใช้ normalize_date แทนเมื่อคอลัมน์เป็นวันที่ที่รูปแบบกำกวม