在导入Excel表格时从string末尾删除空格时出现不正常的行为
我正在导入一个带有空格的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)
但是,在较大的文件上尝试脚本时,parsing第一列'ID'
不会删除空格。
file = 'http://www.camminiepercorsi.com/wp-content/uploads/excel_test/DRS_IL_startingpoint.xlsx' df = parse_excel_sheet(file,'test') print(df)
我只是运行你的代码,发现在更大的文件中,空格被正确地从'ID'列中删除:
for i, el in enumerate(df['ID'].values): # print(i) if " " in el: print(el)
“ID”列没有返回元素:这28个元素没有空格。 你是怎么检查的,情况并非如此?