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

Python - ลบช่องว่างนำหน้าและท้ายใน Pandas DataFrame ด้วย strip()


หากต้องการลบช่องว่างนำหน้า (leading) หรือท้าย (trailing) ในคอลัมน์ของ DataFrame ให้ใช้เมธอด str.strip() ก่อนอื่นต้อง import pandas

import pandas as pd

สร้าง DataFrame ตัวอย่างที่มีคอลัมน์ 'Product Category' มีช่องว่างนำหน้าและท้าย

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]})

ลบช่องว่างในคอลัมน์ 'Product Category' เดียว

dataFrame['Product Category'].str.strip()

ตัวอย่างสมบูรณ์

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 a single column
dataFrame['Product Category'].str.strip()
# dataframe
print("Dataframe after removing whitespaces...\n", dataFrame)

ผลลัพธ์

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