Computer >> Máy Tính >  >> Lập trình >> Python

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

Để loại bỏ khoảng trắng, dù ở đầu hay cuối, hãy sử dụng phương thức dải (). Lúc đầu, hãy để chúng tôi nhập thư viện Pandas được yêu cầu với bí danh -

import pandas as pd

Hãy tạo DataFrame với 3 cột. Cột đầu tiên có khoảng trắng ở đầu và cuối -

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 một cột duy nhất “Danh mục sản phẩm” -

dataFrame['Product Category'].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 a single column
dataFrame['Product Category'].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