Python Pandas – 从多列中删除前导和尾随空格
要删除前导或尾随空格,请使用strip()方法。首先,创建一个包含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() dataFrame['Product Name'].str.strip()
示例
以下是完整的代码-
import pandas as pd
#createadataframewith3columns
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]})
#removingwhitespacefrommorethan1column
dataFrame['Product Category'].str.strip()
dataFrame['Product Name'].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
热门推荐
10 订婚作文祝福语简短英文
11 部队牛年祝福语简短的
12 员工喜事祝福语简短精辟
13 春节最美古文祝福语简短
14 客户开店祝福语简短大气
15 艺校元旦祝福语大全简短
16 称赞老师的祝福语简短
17 感谢母亲祝福语 简短精辟
18 竞选班长祝福语简短精辟