Drop Constant Columns
drop_constant_columns · columns · any
2026-09-23
กำลังประมวลผล…
drop_constant_columns · columns · any
2026-09-23
คอลัมน์ที่ทุกแถวมีค่าเดียวกันไม่ให้ข้อมูลเพิ่มเลย เช่น คอลัมน์ country ที่เป็น Thailand ทั้งไฟล์ หรือคอลัมน์ export_version ที่ระบบใส่มาให้ การลบออกทำให้ตารางกระชับขึ้นและเห็นคอลัมน์ที่มีความหมายจริงได้ง่ายขึ้น
1 กับ "1" ถือว่าต่างกัน และคอลัมน์นั้นจะไม่ถูกลบincludeAllNull เพราะบางครั้ง "ว่างทั้งคอลัมน์" เป็นข้อมูลที่ต้องรายงาน| Parameter | Type | Default |
|---|---|---|
includeAllNull | boolean | false |
import json
def drop_constant_columns(columns, include_all_null=False):
kept = []
for name, values in columns.items():
if not values:
kept.append(name)
continue
first = values[0]
same = all(type(v) is type(first) and v == first for v in values)
if same and (include_all_null or first is not None):
continue
kept.append(name)
return kept
columns = {
'country': ['ไทย', 'ไทย'],
'mixed': [1, '1'],
'empty': [None, None],
}
result = {
'default': drop_constant_columns(columns),
'include_all_null': drop_constant_columns(columns, include_all_null=True),
}
print(json.dumps(result, ensure_ascii=False))
ไฟล์ส่งออกรายเดือนมี 31 คอลัมน์ รัน drop_constant_columns แล้วดูรายชื่อคอลัมน์ที่จะถูกลบใน Preview ถ้าเห็นคอลัมน์อย่าง report_month ที่เป็นค่าเดียวเพราะไฟล์นี้มีเดือนเดียว ให้คิดก่อนว่าจะรวมไฟล์หลายเดือนในอนาคตหรือไม่ ถ้าใช่ ควรเก็บคอลัมน์นั้นไว้
ใช้ drop_sparse_columns สำหรับคอลัมน์ที่ข้อมูลหายเยอะ ใช้ remove_column เมื่อรู้ว่าจะลบคอลัมน์ไหน และใช้ detect_null_like ก่อนเพื่อให้ค่าที่แปลว่าว่างถูกนับเป็นค่าว่างจริง