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

Xóa phần tử chứa đúng 2 khoảng trắng trong Series Python

Mô tả bài toán

Cho Series:

0    This is pandas
1    python script
2    pandas series

Yêu cầu: Xóa các phần tử chứa chính xác 2 khoảng trắng. Kết quả giữ lại: python script (1 khoảng trắng), pandas series (1 khoảng trắng).

Giải pháp 1: Regex + filter (cách gốc)

import pandas as pd
import re

l = ["This is pandas","python script","pandas series"]
data = pd.Series(l)

# Regex tìm tất cả khoảng trắng, đếm số lượng
result = pd.Series(filter(lambda x: len(re.findall(r" ", x)) != 2, data))
print(data[data.isin(result)])

Giải pháp 2: Vòng lặp + pop (cách gốc sửa đổi)

import pandas as pd

l = ["This is pandas","python script","pandas Series"]
data = pd.Series(l)

# Lưu ý: pop() trên Series không thay đổi index tự động, cần reset_index
indices_to_drop = []
for idx, val in data.items():
    if val.count(' ') == 2:
        indices_to_drop.append(idx)

data = data.drop(indices_to_drop).reset_index(drop=True)
print(data)

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

import pandas as pd

data = pd.Series(["This is pandas","python script","pandas series"])

# Tạo mask: True = giữ lại (số space != 2)
mask = data.str.count(' ') != 2
result = data[mask].reset_index(drop=True)
print(result)

Đầu ra

1    python script
2    pandas series
dtype: object

Lưu ý quan trọng: Code gốc dùng data.pop(i) trong vòng lặp có thể gây lỗi index do Series thay đổi kích thước khi duyệt. Cách an toàn là thu thập index cần xóa rồi drop một lần, hoặc dùng boolean masking như giải pháp 3.