Skip to content

String Operations

ข้อมูลข้อความมักมาในรูปแบบไม่สม่ำเสมอ — ช่องว่างเกิน, ตัวเล็กตัวใหญ่ผสม, รูปแบบต่างกัน pandas มี .str accessor ที่ช่วยจัดการข้อความทั้ง column ได้ทีเดียว

.str accessor — ใช้ string method กับทั้ง Series

Section titled “.str accessor — ใช้ string method กับทั้ง Series”
import pandas as pd
df = pd.DataFrame({
"name": [" Alice ", " BOB", "charlie ", " Diana "],
"email": ["ALICE@mail.com", "bob@MAIL.com", "Charlie@Mail.COM", None],
"zipcode": ["1234", "567", "89012", "3456"]
})

.str.strip() / .str.lower() / .str.upper()

Section titled “.str.strip() / .str.lower() / .str.upper()”
# ลบช่องว่างหัวท้าย
df["name"] = df["name"].str.strip()
print(df["name"]) # ['Alice', 'BOB', 'charlie', 'Diana']
# แปลงเป็นตัวเล็ก/ใหญ่
df["name"] = df["name"].str.lower()
df["email"] = df["email"].str.lower()
print(df["name"]) # ['alice', 'bob', 'charlie', 'diana']
# Title case
df["name"] = df["name"].str.title()
print(df["name"]) # ['Alice', 'Bob', 'Charlie', 'Diana']

.str.contains() — ค้นหาข้อความ

Section titled “.str.contains() — ค้นหาข้อความ”
# ค้นหาชื่อที่มี "li"
mask = df["name"].str.contains("li", case=False, na=False)
print(df[mask]) # Alice, Charlie
# ใช้ regex ได้
gmail = df[df["email"].str.contains(r"@gmail\.com", na=False)]

.str.replace() — แทนที่ข้อความ

Section titled “.str.replace() — แทนที่ข้อความ”
# ลบอักขระพิเศษ
df["phone"] = pd.Series(["081-234-5678", "(02) 123 4567", "0891234567"])
df["phone_clean"] = df["phone"].str.replace(r"[\s\-\(\)]", "", regex=True)
print(df["phone_clean"])
# ['0812345678', '021234567', '0891234567']
# แทนที่คำ
df["region"] = pd.Series(["กทม.", "กทม", "กรุงเทพ", "กรุงเทพฯ"])
df["region"] = df["region"].str.replace(r"กทม\.?|กรุงเทพฯ?", "กรุงเทพมหานคร", regex=True)

.str.zfill() — เติม 0 นำหน้า

Section titled “.str.zfill() — เติม 0 นำหน้า”
# เติม 0 ให้ครบ 5 หลัก (เช่น zipcode)
df["zipcode"] = df["zipcode"].str.zfill(5)
print(df["zipcode"])
# ['01234', '00567', '89012', '03456']

String Methods ที่ใช้บ่อย

Section titled “String Methods ที่ใช้บ่อย”
Methodใช้ทำอะไร
.str.len()ความยาวข้อความ
.str.split(",")แยกข้อความ
.str.startswith("A")ขึ้นต้นด้วย
.str.extract(r"(\d+)")ดึงตัวเลขออกมา
.str.slice(0, 3)ตัดข้อความ