Mô tả bài toán
Cho Series:
0 12 1 13 2 15 3 20 4 19 5 18 6 11
Yêu cầu: Lọc các phần tử có giá trị trong khoảng [10, 15]. Kết quả: 12, 13, 15, 11.
Giải pháp 1: Dùng between() (khuyên dùng)
import pandas as pd
l = [12,13,15,20,19,18,11]
data = pd.Series(l)
print("Series gốc:")
print(data)
# between(10, 15) mặc định inclusive=True (bao gồm cả 2 đầu)
result = data[data.between(10, 15)]
print("\nPhần tử trong khoảng [10, 15]:")
print(result)
Giải pháp 2: Vòng lặp + isin() (cách gốc)
import pandas as pd
l = [12,13,15,20,19,18,11]
data = pd.Series(l)
ls = []
for i in range(len(data)):
if data[i] >= 10 and data[i] <= 15:
ls.append(data[i])
result = data[data.isin(ls)]
print(result)
Giải pháp 3: Boolean indexing trực tiếp
import pandas as pd data = pd.Series([12,13,15,20,19,18,11]) mask = (data >= 10) & (data <= 15) result = data[mask] print(result)
Đầu ra (tất cả cách cho cùng kết quả)
0 12 1 13 2 15 6 11 dtype: int64
So sánh
| Phương pháp | Độ phức tạp | Hiệu năng | Ghi chú |
|---|---|---|---|
| between() | Thấp | Cao | Đọc dễ, inclusive tùy chỉnh |
| Boolean mask | Thấp | Cao | Linh hoạt điều kiện phức tạp |
| Vòng lặp + isin | Cao | Thấp | Không khuyên cho dữ liệu lớn |
Lưu ý: between(left, right, inclusive='both') có tham số inclusive ('both', 'neither', 'left', 'right') từ pandas 1.3+.