【问题标题】:Erratic behaviour when removing whitespace from the end of a string while importing excel table导入 excel 表时从字符串末尾删除空格时出现异常行为
【发布时间】: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()函数(但它从来没有工作过。不过你的!谢谢!
  • 很高兴为您提供帮助! :)

标签: excel pandas stripping


【解决方案1】:

我刚刚运行了您的代码,发现空格已从较大文件中的“ID”列中正确删除:

for i, el in enumerate(df['ID'].values):
# print(i)
if " " in el:
    print(el)

不返回“ID”列中的任何元素:这 28 个元素中没有空格。 您是如何确认不是这种情况的?

【讨论】:

  • 谢谢。我通过导出到 csv 文件并使用文本编辑器(例如 notepad++)打开这些文件来检查空格
  • 如果我给你发了一个链接,你能试着解析整个文件吗?
  • 不,但我认为问题不在您上面的代码中:此代码正确删除了该列中的空格。
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 2023-01-04
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多