Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lọc phần tử trong khoảng giá trị cho trước từ Series Python

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ạpHiệu năngGhi chú
between()ThấpCaoĐọc dễ, inclusive tùy chỉnh
Boolean maskThấpCaoLinh hoạt điều kiện phức tạp
Vòng lặp + isinCaoThấpKhô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+.