Python Pandas - 去除多列中前后空白
若想去除前后空白,请使用 strip() 方法。首先,创建一个包含 3 列“产品种类”、“产品名称”和“数量”的数据框 −
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
# 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 more than 1 column
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP