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]})
从单列“产品类别”中删除空格 -
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
以上是 Python – 从 Pandas DataFrame 中去除空格 的全部内容, 来源链接: utcz.com/z/360366.html