Reading CSV
Reading CSV
Section titled “Reading CSV”ไฟล์ CSV เป็นรูปแบบที่พบบ่อยที่สุดในงาน Data การอ่านให้ถูกต้องตั้งแต่แรกจะช่วยประหยัดเวลา clean ข้อมูลอย่างมาก
อ่านแบบพื้นฐาน
Section titled “อ่านแบบพื้นฐาน”import pandas as pd
df = pd.read_csv("sales.csv")df.info()กำหนด dtype — ป้องกัน auto-detection ผิดพลาด
Section titled “กำหนด dtype — ป้องกัน auto-detection ผิดพลาด”# รหัสไปรษณีย์ เช่น "01234" ถ้าไม่กำหนด dtype จะถูกอ่านเป็น int → 1234df = pd.read_csv("customers.csv", dtype={ "zipcode": str, "phone": str, "customer_id": str})จัดการ missing values ตั้งแต่ตอนอ่าน
Section titled “จัดการ missing values ตั้งแต่ตอนอ่าน”# pandas จะถือ NA, N/A, null เป็น NaN อัตโนมัติ# แต่ข้อมูลจริงอาจใช้คำอื่นdf = pd.read_csv("data.csv", na_values=[ "N/A", "n/a", "-", "ไม่ระบุ", "NULL", ""])parse_dates — แปลง column เป็น datetime ทันที
Section titled “parse_dates — แปลง column เป็น datetime ทันที”df = pd.read_csv("orders.csv", parse_dates=["order_date", "ship_date"])print(df.dtypes)# order_date datetime64[ns]# ship_date datetime64[ns]ตัวเลือกที่ใช้บ่อย
Section titled “ตัวเลือกที่ใช้บ่อย”df = pd.read_csv( "data.csv", encoding="utf-8-sig", # รองรับภาษาไทย + BOM sep=",", # ตัวคั่น (default คือ comma) usecols=["col1", "col2"], # อ่านเฉพาะ column ที่ต้องการ nrows=1000, # อ่านแค่ 1000 แถวแรก (ทดสอบ) skiprows=1, # ข้ามแถวแรก)- เปิดไฟล์ CSV ได้ตรงๆ ผ่าน File > Import
- ไม่สามารถกำหนด dtype ได้ — ต้อง format column เอง
- ใช้
=IMPORTDATA("url")เพื่อดึง CSV จาก URL
-- PostgreSQLCOPY sales FROM '/path/to/sales.csv' CSV HEADER;-- หรือใช้ \copy ใน psql\copy sales FROM 'sales.csv' WITH CSV HEADER// C ต้อง parse CSV เอง ทีละ characterFILE *fp = fopen("sales.csv", "r");char line[1024];while (fgets(line, 1024, fp)) { // strtok(line, ",") แยกแต่ละ field}fclose(fp);