Để xóa khoảng trắng ở đầu hoặc cuối, hãy sử dụng phương thức dải (). Đầu tiên, hãy tạo DataFrame với 3 cột “Danh mục sản phẩm”, “Tên sản phẩm” và “Số lượng” -
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 khỏi nhiều cột -
dataFrame['Product Category'].str.strip() dataFrame['Product Name'].str.strip()
Ví dụ
Sau đây là mã hoàn chỉnh -
import pandas as pd
# create a dataframe with 3 columns
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]})
# removing whitespace from more than 1 column
dataFrame['Product Category'].str.strip()
dataFrame['Product Name'].str.strip()
# dataframe
print"Dataframe after removing whitespaces...\n",dataFrame Đầu ra
Điều này sẽ tạo ra kết quả sau -
Dataframe after removing whitespaces... 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