Mô tả bài toán
Cho Series:
0 apple 1 oranges 2 alpha 3 aroma 4 beta
Yêu cầu: Lọc các chuỗi bắt đầu bằng 'a' VÀ kết thúc bằng 'a'. Kết quả: alpha, aroma.
Giải pháp 1: Regex với re.search
Biểu thức chính quy: r'^[a].*[a]$' (bắt đầu 'a', kết thúc 'a').
import pandas as pd
import re
l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)
exp = r'^[a].*[a]$' # ^a...a$
ls = []
for i in data:
if re.search(exp, i):
ls.append(i)
result = data[data.isin(ls)]
print(result)
Giải pháp 2: Dùng startswith/endswith (khuyên dùng - dễ đọc hơn)
import pandas as pd
l = ["apple","oranges","alpha","aroma","beta"]
data = pd.Series(l)
# Dùng filter + lambda
filtered = list(filter(lambda x: x.startswith('a') and x.endswith('a'), l))
result = data[data.isin(filtered)]
print(result)
# Hoặc vector hóa với str accessor (hiệu quả nhất)
mask = data.str.startswith('a') & data.str.endswith('a')
result = data[mask]
print(result)
Đầu ra
2 alpha 3 aroma dtype: object
So sánh phương pháp
| Phương pháp | Độ phức tạp | Hiệu năng | Khuyên dùng |
|---|---|---|---|
| Regex + vòng lặp | Trung bình | Thấp | Khi pattern phức tạp |
| startswith/endswith + filter | Dễ hiểu | Trung bình | Code rõ ràng |
| str accessor vector hóa | Đơn giản | Cao | Khuyên dùng nhất |