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
广告