Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas – ลบ Whitespace นำหน้าและท้ายจากหลายคอลัมน์ (strip)

ภาพรวม

ใช้ 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

ประยุกต์: Strip ทุกคอลัมน์ object พร้อมกัน


# หาคอลัมน์ที่เป็น object/string
obj_cols = df.select_dtypes(include=['object']).columns

# Apply strip ทั้งหมด
for col in obj_cols:
    df[col] = df[col].str.strip()

# หรือ one-liner
df[obj_cols] = df[obj_cols].apply(lambda x: x.str.strip())

หมายเหตุ

  • .str.strip() คืน Series ใหม่ ต้อง assign กลับ
  • NaN values จะคงเดิม (ไม่ error)
  • ใช้ .str.strip().str.lower() chain ได้
Methodคำอธิบาย
.str.strip()ลบ whitespace ทั้งหน้าและหลัง
.str.lstrip()ลบ whitespace นำหน้า (leading)
.str.rstrip()ลบ whitespace ท้าย (trailing)
.str.strip(chars)ลบตัวอักษรที่ระบุ (ไม่ใช่แค่ whitespace)