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

Lọc chỉ các phần tử số nguyên trong Series Python

Mô tả bài toán

Cho Series hỗn hợp:

0      1
1      2
2    python
3    pandas
4      3
5      4
6      5

Yêu cầu: Lọc ra chỉ các phần tử kiểu integer. Kết quả: 1, 2, 3, 4, 5.

Giải pháp 1: Vòng lặp kiểm tra type (cách gốc - đơn giản)

import pandas as pd

ls = [1, 2, "python", "pandas", 3, 4, 5]
data = pd.Series(ls)

print("Chỉ các phần tử integer:")
for idx, val in data.items():
    if type(val) == int:
        print(idx, val)

Giải pháp 2: Regex + filter (cách gốc phức tạp)

Chuyển tất cả về string, dùng regex r'\d+' khớp toàn bộ chuỗi số.

import pandas as pd
import re

ls = [1, 2, "python", "pandas", 3, 4, 5]
data = pd.Series(ls)

result = pd.Series(filter(lambda x: re.match(r"\d+", str(x)), data))
print(data[data.isin(result)])

Giải pháp 3: Vector hóa apply(type) (khuyên dùng)

import pandas as pd

data = pd.Series([1, 2, "python", "pandas", 3, 4, 5])

# Tạo mask boolean
mask = data.apply(type) == int
result = data[mask]
print("Kết quả (vector hóa):")
print(result)

# Reset index nếu cần
print("\nReset index:")
print(result.reset_index(drop=True))

Đầu ra

Kết quả (vector hóa):
0    1
1    2
4    3
5    4
6    5
dtype: object

Reset index:
0    1
1    2
2    3
3    4
4    5
dtype: object

Mở rộng: Lọc cả số thực (float) coi như số

import pandas as pd
import numbers

data = pd.Series([1, 2.5, "python", 3, 4.0, 5])
# Kiểm tra isinstance Number (int, float, complex)
mask = data.apply(lambda x: isinstance(x, numbers.Number) and not isinstance(x, bool))
print(data[mask])

Lưu ý: bool là subclass của int trong Python, nên type(True) == int là False nhưng isinstance(True, int) là True. Cần loại trừ bool nếu không muốn coi True/False là số.