จัดการไฟล์ CSV ให้คลีนด้วย pandas read_csv() ฉบับมือโปร

· By: SirilukP

From Messy to Clean: Taming Real-World CSV Files with pandas read_csv()

Introduction

ใครก็ตามที่คลุกคลีกับการทำงานด้าน real-world data science มาสักระยะ คงจะทราบดีว่าชุดข้อมูลที่สะอาดและจัดรูปแบบเป็นระเบียบในไฟล์ CSV นั้นแทบจะเป็นเรื่องในอุดมคติ

ข้อมูลในโลกแห่งความเป็นจริงมักมาในรูปแบบที่จัดการยาก ตั้งแต่ metadata ไร้ประโยชน์ที่ส่วนหัวของไฟล์ ไปจนถึงการใช้เครื่องหมาย semicolon ปะปนกับ comma รวมถึงข้อผิดพลาดในการจัดรูปแบบต่างๆ ยิ่งไปกว่านั้น ไฟล์ข้อมูลขององค์กรหรือชุดข้อมูลเปิดมักมีขนาดใหญ่มากจนทำให้ Python notebook แครชเมื่อพยายามวิเคราะห์ ซึ่งปัญหาเหล่านี้มักเกิดขึ้นก่อนที่เราจะได้เริ่มดูเนื้อหาข้อมูลจริงๆ เสียด้วยซ้ำ

บทความนี้จะแสดงขั้นตอนการสร้างตัวโหลด Python ที่แข็งแกร่งโดยอิงจากฟังก์ชัน pandas read_csv() เพื่อเปลี่ยนข้อมูลที่ยุ่งเหยิงให้สะอาดพร้อมใช้งาน โดยเราจะใช้ชุดข้อมูลเปิด NYC Airbnb เป็นตัวอย่างของความโกลาหลในข้อมูลที่สร้างโดยผู้ใช้

  • ขั้นแรก เราจะวิเคราะห์ปัญหาทั่วไปในการอ่านไฟล์ CSV ทีละประเด็นในเชิงแนวคิด
  • จากนั้น เราจะรวบรวมแนวคิดทั้งหมดสร้างเป็นฟังก์ชันตัวโหลดที่ประหยัดหน่วยความจำและนำกลับมาใช้ใหม่ได้ ซึ่งคุณสามารถคัดลอกไปปรับใช้กับโปรเจกต์ data science ของคุณได้ทันที พร้อมแสดงผลลัพธ์จากการใช้งานจริงกับชุดข้อมูล Airbnb

Tackling Common CSV Reading Issues

ในสภาพแวดล้อมที่มีทรัพยากรจำกัด ข้อจำกัดของ RAM คืออุปสรรคแรกเมื่อต้องจัดการกับไฟล์ขนาดใหญ่ การรัน pd.read_csv() บนไฟล์ขนาด 10GB อาจทำให้ execution kernel พังได้ง่ายๆ เราจึงต้องใช้กลยุทธ์เชิงรับอย่างพารามิเตอร์ chunksize ซึ่งจะทำให้ read_csv() คืนค่าเป็น iterator เพื่อประมวลผลข้อมูลเป็นส่วนๆ (chunks) ที่จัดการได้ง่าย มาลองดูตัวอย่าง chunk แรกกัน:

import pandas as pd
 
# NYC Airbnb Dataset (~7MB): Messy, user-generated data
DATA_URL = "https://raw.githubusercontent.com/alexeygrigorev/datasets/master/AB_NYC_2019.csv"
 
# Prototyping: Reading in chunks of 10,000 rows at a time
df_chunks = pd.read_csv(DATA_URL, chunksize=10000)
 
# Pulling the first chunk to see what's inside
first_chunk = next(df_chunks)
 
print(f"First chunk shape: {first_chunk.shape}")
print(first_chunk.head())

Example output:

First chunk shape: (10000, 16)
     id                                              name  host_id  
0  2539                Clean & quiet apt home by the park     2787
1  2595                             Skylit Midtown Castle     2845
2  3647               THE VILLAGE OF HARLEM....NEW YORK !
3  3831                   Cozy Entire Floor of Brownstone     4869
4  5022  Entire Apt: Spacious Studio/Loft by central park     7192
 
host_name neighbourhood_group neighbourhood  latitude  longitude  
0         John            Brooklyn    Kensington  40.64749  -73.97237
1     Jennifer           Manhattan       Midtown  40.75362  -73.98377
2    Elisabeth           Manhattan        Harlem  40.80902  -73.94190
3  LisaRoxanne            Brooklyn  Clinton Hill  40.68514  -73.95976
4        Laura           Manhattan   East Harlem  40.79851  -73.94399
 
room_type  price  minimum_nights  number_of_reviews last_review  
0     Private room    149               1                  9  2018-10-19
1  Entire home/apt    225               1                 45  2019-05-21
2     Private room    150               3                  0         NaN
3  Entire home/apt     89               1                270  2019-07-05
4  Entire home/apt     80              10                  9  2018-11-19
 
reviews_per_month  calculated_host_listings_count  availability_365
0               0.21                               6               365
1               0.38                               2               355
2                NaN                               1               365
3               4.64                               1               194
4               0.10                               1                 0

จากการดูข้อมูลเบื้องต้นพบว่ามีความยุ่งเหยิงและมีค่าที่ขาดหายไปกระจายอยู่ทั่วไป เราจะสร้างฟังก์ชันที่นำกลับมาใช้ใหม่ได้เพื่อจัดการปัญหานี้ให้สะอาดขึ้นในตอนท้าย แต่ก่อนอื่น มาสรุปเทคนิคที่มีประโยชน์สำหรับปัญหาแต่ละรูปแบบกันก่อน

Junk header rows: ข้อมูลที่ส่งออกจากเครื่องมืออย่าง SAP หรือแพลตฟอร์มรัฐบาล มักแนบ metadata ไว้ที่ต้นไฟล์ เช่น วันที่สร้างหรือชื่อผู้เขียน ซึ่งจะทำให้ pandas ไม่สามารถระบุโครงสร้างคอลัมน์ (schema) ได้ถูกต้อง ให้ใช้พารามิเตอร์ skiprows เพื่อข้ามบรรทัดที่ไม่จำเป็นและกำหนดจุดเริ่มต้นของหัวตารางที่แท้จริง:

df = pd.read_csv(
    DATA_URL,
    nrows=100,
    skiprows=0 # NOTE: Change this to 2, 3, etc. if your file has several lines of metadata at the top
)

Navigating bad encodings: ตัวอักษรพิเศษหรือเครื่องหมายเน้นเสียงในชุดข้อมูลเปิดมักทำให้เกิดข้อผิดพลาด UnicodeDecodeError ได้ง่าย หากคาดว่าข้อมูลจะมีตัวอักษรเหล่านี้ ให้ใช้ encoding_errors='replace' เพื่อแทนที่ตัวอักษรที่อ่านไม่ได้ด้วยตัวสำรองแทนที่จะปล่อยให้โปรแกรมหยุดทำงาน:

df = pd.read_csv(
    DATA_URL,
    nrows=100,
    encoding='utf-8',
    encoding_errors='replace' # Keeps the kernel alive when hitting bad bytes
)

Mixed delimiters: หากไฟล์มีการใช้ตัวคั่นที่หลากหลาย เช่น comma, semicolon หรือ pipe ให้ส่ง regular expression character class เช่น '[...]' เพื่อระบุตัวแยกทั้งหมด:

df = pd.read_csv(
    DATA_URL,
    nrows=100,
    engine='python',        # Required for regex separators
    sep=r'[,;\|]',          # Splits on comma, semicolon, or pipe
    on_bad_lines='skip'     # Skips rows that get mangled by the regex
)

Thousands separators in large numbers: ในข้อมูลการเงิน ตัวเลขมักถูกเก็บเป็น string พร้อมเครื่องหมาย comma เช่น "1,000,235.00" ซึ่งคำนวณไม่ได้ ให้ใช้พารามิเตอร์ thousands เพื่อกำจัดเครื่องหมายเหล่านี้โดยอัตโนมัติ:

df = pd.read_csv(
    DATA_URL,
    nrows=100,
    thousands=',' # Strips commas from numbers automatically
)

Parsing mixed date formats: สำหรับวันที่ที่มีหลายรูปแบบในไฟล์เดียว เช่น MM/DD/YYYY ปนกับ June 29, 2026 คุณสามารถใช้ date_format='mixed' (ใน pandas 2.0+) เพื่อให้ระบบประมวลผลวันที่ให้อัตโนมัติ:

df = pd.read_csv(
    DATA_URL,
    nrows=100,
    parse_dates=['last_review'], # The Airbnb dataset tracks when properties were last reviewed
    date_format='mixed'          # Intelligently handles varying datetime formats
)

Bringing It All Together

ถึงเวลารวบรวมกลยุทธ์ทั้งหมดเข้าด้วยกันเป็นฟังก์ชันเดียวที่แข็งแกร่งและนำกลับมาใช้ใหม่ได้ ลองนำโค้ดด้านล่างไปรันใน Python notebook เพื่อดูประสิทธิภาพการจัดการชุดข้อมูล Airbnb:

import pandas as pd
 
def load_and_clean_messy_csv(file_url, chunk_size=10000):
    """
    A robust loader for messy, massive CSV files.
    Yields cleaned pandas DataFrames in manageable chunks.
    """
    print(f"Initializing bulletproof loader for: {file_url}")
 
# Creating the chunk iterator with our defensive parameters
    chunk_iterator = pd.read_csv(
        file_url,
 
# 1. Memory management (prevents kernel crashes on huge files)
        chunksize=chunk_size,
        low_memory=False,
 
# 2. Bypassing junk (set to 0 here, adjust for SAP/enterprise exports)
        skiprows=0,
 
# 3. Bad encodings (prevents fatal read errors on emojis/special chars)
        encoding='utf-8',
        encoding_errors='replace',
 
# 4. Delimiters (uncomment the line below if your dataset file mixes commas and semicolons,
        #    and remove low_memory=False above, which the python engine doesn't support)
        # sep=r'[,;\|]', engine='python',
 
# 5. Thousands separators (cleans numeric strings on import)
        thousands=',',
 
# 6. Mixed date formats (intelligently parses messy date columns)
        parse_dates=['last_review'],
        date_format='mixed',
 
# Bonus: Skipping severely corrupted lines that have too many columns
        on_bad_lines='skip'
    )
 
return chunk_iterator
 
# --- Execution ---
if __name__ == "__main__":
    # Lightweight, real-world dataset (loads in ~2 seconds)
    AIRBNB_URL = "https://raw.githubusercontent.com/alexeygrigorev/datasets/master/AB_NYC_2019.csv"
 
# Initialize the robust loader
    df_chunks = load_and_clean_messy_csv(AIRBNB_URL, chunk_size=15000)
 
# Process the chunks
    for i, chunk in enumerate(df_chunks):
        print(f"\n--- Successfully loaded Chunk {i+1} ---")
        print(f"Shape: {chunk.shape}")
 
if i == 0:
            # Print a preview of the clean data on the first pass
            print("\nCleaned Data Preview (Notice the 'last_review' dates are properly formatted):")
            print(chunk[['name', 'neighbourhood_group', 'price', 'last_review']].head())
 
# We will stop after 2 chunks just to prove the iteration works
        if i == 1:
            print("\nChunking successful. Exiting loop.")
            break

Output:

Initializing bulletproof loader for: https://raw.githubusercontent.com/alexeygrigorev/datasets/master/AB_NYC_2019.csv
 
--- Successfully loaded Chunk 1 ---
Shape: (15000, 16)
 
Cleaned Data Preview (Notice the 'last_review' dates are properly formatted):
                                               name neighbourhood_group  
0                Clean & quiet apt home by the park            Brooklyn
1                             Skylit Midtown Castle           Manhattan
2               THE VILLAGE OF HARLEM....NEW YORK !           Manhattan
3                   Cozy Entire Floor of Brownstone            Brooklyn
4  Entire Apt: Spacious Studio/Loft by central park           Manhattan
 
price last_review
0    149  2018-10-19
1    225  2019-05-21
2    150         NaT
3     89  2019-07-05
4     80  2018-11-19
 
--- Successfully loaded Chunk 2 ---
Shape: (15000, 16)
 
Chunking successful. Exiting loop.

ผลลัพธ์นี้แสดงให้เห็นจุดสำคัญคือ pandas สามารถแบ่งข้อมูลเป็นชุด (batches) ละ 15,000 แถวได้อย่างราบรื่น มีการจัดการวันที่ให้เป็นรูปแบบ YYYY-MM-DD ที่สอดคล้องกัน โดยใช้ NaT แทนค่าวันที่ที่ขาดหายไป ซึ่งยืนยันว่าข้อมูลถูกแปลงเป็นออบเจกต์ datetime โดยสมบูรณ์ นอกจากนี้ทั้งข้อความและตัวเลขยังจัดเรียงในคอลัมน์ได้อย่างถูกต้อง

Wrapping Up

บทความนี้สรุปเทคนิคการจัดการคุณภาพและความสอดคล้องของข้อมูลตั้งแต่ขั้นตอนการโหลดไฟล์เข้าสู่ pandas พร้อมทั้งรวมกลยุทธ์ต่างๆ เข้าเป็นฟังก์ชันที่ใช้งานได้ครอบคลุม เพื่อช่วยให้การวิเคราะห์ข้อมูลของคุณมีความมั่นคงและมีประสิทธิภาพยิ่งขึ้น

Source: KDnuggets
ดูแลงานแปลและเรียบเรียงโดย SirilukP

ความคิดเห็น (0)

เข้าสู่ระบบเพื่อร่วมแสดงความเห็น

สมัครสมาชิก

มาเป็นคนแรกที่แสดงความเห็นกันเลยโบร