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

Python Pandas – Loại bỏ khoảng trắng đầu/cuối của nhiều cột

Giới thiệu

Để xóa khoảng trắng thừa ở đầu và cuối chuỗi của nhiều cột string trong DataFrame, dùng accessor .str.strip() trên từng cột.

Ví dụ minh họa

import pandas as pd

# DataFrame có khoảng trắng trong cột string
dataFrame = pd.DataFrame({
    'Product Category': [' Computer', ' Mobile Phone', 'Electronics ', 'Appliances', ' Furniture', 'Stationery'],
    'Product Name': ['Keyboard', 'Charger', ' SmartTV', 'Refrigerators', ' Chairs', 'Diaries'],
    'Quantity': [10, 50, 10, 20, 25, 50]
})

# Xóa whitespace cột Product Category và Product Name
dataFrame['Product Category'] = dataFrame['Product Category'].str.strip()
dataFrame['Product Name'] = dataFrame['Product Name'].str.strip()

print("DataFrame sau strip whitespace:\n", dataFrame)

Kết quả đầu ra

DataFrame sau strip whitespace:
  Product Category Product Name  Quantity
0        Computer     Keyboard        10
1    Mobile Phone     Charger        50
2     Electronics     SmartTV        10
3    Appliances  Refrigerators        20
4      Furniture      Chairs        25
5     Stationery      Diaries        50

Lưu ý: Cần gán lại vào cột (df[col] = df[col].str.strip()) vì str.strip() trả về Series mới, không sửa inplace.