String Operations
String Operations
Section titled “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 casedf["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) | ตัดข้อความ |
=TRIM(A1)— strip=LOWER(A1)/=UPPER(A1)=SEARCH("text", A1)— contains=SUBSTITUTE(A1, "old", "new")— replace=TEXT(A1, "00000")— zfill
TRIM(name), LOWER(name), UPPER(name)WHERE name LIKE '%li%' -- containsREPLACE(phone, '-', '') -- replaceLPAD(zipcode, 5, '0') -- zfill#include <string.h>#include <ctype.h>// C ต้องจัดการ string ด้วยมือ ทีละ characterfor (int i = 0; name[i]; i++) name[i] = tolower(name[i]);