【发布时间】:2018-03-08 17:35:52
【问题描述】:
我正在导入一个在大多数需要删除的单元格内容末尾带有空格的 excel 文件。以下脚本适用于示例数据:
import pandas as pd
def strip(text):
try:
return text.strip()
except AttributeError:
return text
def num_strip(text):
try:
return text.split(" ",1)[0]
except AttributeError:
return text
def parse_excel_sheet(input_file, sheet):
df = pd.read_excel(
input_file,
sheetname= sheet,
parse_cols = 'A,B,C',
names=['ID', 'name_ITA', 'name_ENG'],
converters = {
'ID' : num_strip,
'name1' : strip,
'name2' : strip,
}
)
return df
file = 'http://www.camminiepercorsi.com/wp-content/uploads/excel_test/excel_test.xlsx'
df = parse_excel_sheet(file,'1')
print(df)
但是,在较大文件上尝试脚本时,解析第一列 'ID' 不会删除空格。
file = 'http://www.camminiepercorsi.com/wp-content/uploads/excel_test/DRS_IL_startingpoint.xlsx'
df = parse_excel_sheet(file,'test')
print(df)
【问题讨论】:
-
更新:如果从 jupyter 控制台执行或使用文本编辑器(即崇高文本)编译,脚本将返回不同的结果。我很不解!
-
导入数据后为什么不这样做...
df.ID = df.ID.str.strip() -
@djk47463 我尝试以多种方式做类似的事情(全部使用
.str和.strip()函数(但它从来没有工作过。不过你的!谢谢! -
很高兴为您提供帮助! :)