Remove Duplicate By Column
remove_duplicate_by_column · duplicates · any
2026-09-23
กำลังประมวลผล…
remove_duplicate_by_column · duplicates · any
2026-09-23
ข้อมูลลูกค้าที่มาจากหลายแหล่งมักมีอีเมลเดียวกันหลายแถว แต่ละแถวกรอกข้อมูลไม่เท่ากัน เทคนิคนี้ยุบให้เหลือแถวเดียวต่อหนึ่งกุญแจ และให้คุณเลือกว่ากติกาการเก็บคือแถวแรก แถวสุดท้าย หรือแถวที่มีข้อมูลครบที่สุด
keyColumns โดยแยกชนิดข้อมูล — 1 กับ "1" ไม่ใช่ค่าเดียวกัน และ null ไม่ใช่ ""keep แล้วลบที่เหลือ โดย max_completeness นับจำนวนช่องที่ไม่ใช่ null ของทั้งแถว ถ้าเท่ากันจะได้แถวที่มาก่อน| Parameter | Type | Default |
|---|---|---|
keyColumns | string[] | — |
keep | first | last | max_completeness | "first" |
import json
def remove_duplicate_by_column(rows, key_columns, keep='first'):
groups = {}
for index, row in enumerate(rows):
key = json.dumps([row.get(c) for c in key_columns], ensure_ascii=False)
groups.setdefault(key, []).append(index)
def filled(index):
return sum(1 for value in rows[index].values() if value is not None)
winners = set()
for indexes in groups.values():
if keep == 'last':
winners.add(indexes[-1])
elif keep == 'max_completeness':
winners.add(max(indexes, key=lambda i: (filled(i), -i)))
else:
winners.add(indexes[0])
return [row for index, row in enumerate(rows) if index in winners]
rows = [
{'email': 'a@x.com', 'name': 'A', 'phone': None},
{'email': 'a@x.com', 'name': 'A2', 'phone': '02'},
{'email': 'b@x.com', 'name': 'B', 'phone': None},
]
result = remove_duplicate_by_column(rows, ['email'], 'max_completeness')
print(json.dumps(result, ensure_ascii=False))
รายชื่อผู้สมัคร 5,000 แถวมีอีเมลซ้ำ 312 อีเมล เลือก keyColumns เป็น email และ keep เป็น max_completeness เพื่อเก็บแถวที่กรอกเบอร์โทรและที่อยู่ไว้แล้ว ก่อนรัน ให้ใช้ validate_email ตั้ง lowercase เพื่อไม่ให้ A@x.com กับ a@x.com ถูกนับเป็นคนละคน
ใช้ remove_duplicate_rows เมื่อต้องการให้เหมือนกันทุกคอลัมน์ ใช้ find_fuzzy_duplicates เมื่อกุญแจพิมพ์ไม่ตรงกันเป๊ะ และใช้ find_similar_values ก่อนเพื่อรวมค่าที่สะกดต่างกัน