การรวม (Merge/Concatenate) ไฟล์ CSV หลายไฟล์เป็น DataFrame เดียว ทำได้ง่ายด้วย pd.concat() ร่วมกับ map(pd.read_csv, file_list) หรือ List Comprehension
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีและกำหนด path ไฟล์
import pandas as pd
file1 = r"C:\Users\amit_\Desktop\sales1.csv"
file2 = r"C:\Users\amit_\Desktop\sales2.csv"
2. รวมด้วย pd.concat + map
dataFrame = pd.concat(
map(pd.read_csv, [file1, file2]),
ignore_index=True
)
print(dataFrame)
โค้ดตัวอย่างสมบูรณ์
import pandas as pd
file1 = r"C:\Users\amit_\Desktop\sales1.csv"
file2 = r"C:\Users\amit_\Desktop\sales2.csv"
print("Merging multiple CSV files...")
dataFrame = pd.concat(
map(pd.read_csv, [file1, file2]),
ignore_index=True
)
print(dataFrame)
ผลลัพธ์
Car Place UnitsSold
0 Audi Bangalore 80
1 Porsche Mumbai 110
2 RollsRoyce Pune 100
3 BMW Delhi 95
4 Mercedes Hyderabad 80
5 Lamborghini Chandigarh 80
วิธีอื่นๆ ที่แนะนำ
# 1. List Comprehension (อ่านง่าย กว้างขวาง)
files = [file1, file2, file3]
dfs = [pd.read_csv(f) for f in files]
combined = pd.concat(dfs, ignore_index=True)
# 2. Glob + Concat (อ่านทั้งโฟลเดอร์)
import glob
files = glob.glob(r"C:\path\*.csv")
combined = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
# 3. เพิ่มคอลัมน์ต้นทาง
dfs = [pd.read_csv(f).assign(source=f) for f in files]
combined = pd.concat(dfs, ignore_index=True)
# 4. Chunked reading (ไฟล์ใหญ่)
chunks = []
for f in files:
for chunk in pd.read_csv(f, chunksize=10000):
chunks.append(chunk)
combined = pd.concat(chunks, ignore_index=True)
พารามิเตอร์ concat สำคัญ
| พารามิเตอร์ | ค่าเริ่มต้น | คำอธิบาย |
|---|---|---|
ignore_index | False | True = รีเซ็ต index ใหม่ 0,1,2... |
axis | 0 | 0 = ต่อแถว (rows), 1 = ต่อคอลัมน์ (columns) |
join | 'outer' | 'outer' = union columns, 'inner' = intersection |
sort | False | True = เรียงคอลัมน์ alphabetically |
verify_integrity | False | True = error ถ้า index ซ้ำ |
Join: Outer vs Inner
# Outer (default): รวมคอลัมน์ทั้งหมด, ไม่มี = NaN
pd.concat([df1, df2], join='outer')
# Inner: เฉพาะคอลัมน์ที่มีในทั้งสอง
pd.concat([df1, df2], join='inner')
Best Practice
- ใช้
ignore_index=Trueเพื่อ index สะอาด - เพิ่ม
source_filecolumn เพื่อ traceability - ตรวจสอบ schema (dtypes, columns) ก่อน concat
- ไฟล์ใหญ่: ใช้ generator + chunked reading