Python——從 Pandas DataFrame 中刪除空白


要刪除空白,無論是其前導還是後導,請使用 strip() 方法。首先,讓我們使用別名匯入必需的 Pandas 庫−

import pandas as pd

讓我們建立一個有 3 列的 DataFrame。第一列有前導和後導空白 −

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

從單列“ProductCategory”中刪除空白 −

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

更新時間:2021 年 9 月 15 日

852 次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告