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

Python - Loại bỏ khoảng trắng trong Pandas DataFrame

Để xóa khoảng trắng đầu/cuối chuỗi trong cột DataFrame, dùng phương thức str.strip() của Series chuỗi.

Ví dụ

Mã hoàn chỉnh:

import pandas as pd
# Tạo DataFrame
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 khoảng trắng cột Product Category
dataFrame['Product Category'] = dataFrame['Product Category'].str.strip()
print("DataFrame sau khi strip:")
print(dataFrame)

Kết quả

DataFrame sau khi strip:
  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

Giải thích

  • Import pandas, tạo DataFrame có cột chứa khoảng trắng thừa.
  • Áp dụng .str.strip() lên cột cần làm sạch, gán lại.
  • In DataFrame kết quả.