ภาพรวม
ใช้ accessor .str.strip() ลบ whitespace นำหน้าและท้าย (leading/trailing) ของคอลัมน์ string หลายคอลัมน์พร้อมกัน
ตัวอย่างโค้ด
import pandas as pd
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]
})
print("Before strip:")
print(dataFrame)
# Strip หลายคอลัมน์
dataFrame['Product Category'] = dataFrame['Product Category'].str.strip()
dataFrame['Product Name'] = dataFrame['Product Name'].str.strip()
print("\nDataframe after removing whitespaces...\n", dataFrame)
ผลลัพธ์
Before 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
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
String Accessor Methods
| Method | คำอธิบาย |
|---|---|
.str.strip() | ลบ whitespace ทั้งหน้าและหลัง |
.str.lstrip() | ลบ whitespace นำหน้า (leading) |
.str.rstrip() | ลบ whitespace ท้าย (trailing) |
.str.strip(chars) | ลบตัวอักษรที่ระบุ (ไม่ใช่แค่ whitespace) |