Python - 单元格类型 'NoneType' 而值在里面。如何改变它?



在过去的几个小时里,我一直在为此苦苦挣扎。我正在编写一个一次性使用的脚本,希望能为我节省很多时间。 脚本的用途如下:

#In a certain directory, loop through all the .xlsx files
#From each .xlsx file, select a whole column based on the column header (user input) (in this case, a year)
#Copy these columns successively into a new workbook.

我事先使用熊猫将.tsv文件转换为.xlsx文件,如下所示:

# Read tsvfile into dataframe in using panda
df = pandas.read_table(tsvfile)
# New excelfile
writer = ExcelWriter(tsvfile + '.xlsx')
# Write dataframe to excel
df.to_excel(writer, header = True)
writer.save()

这工作得很好,我现在有多个.xlsx文件,可以在不更改数据的情况下打开。问题是根据excel,单元格值已以文本格式保存。尝试在我的 python 脚本中使用这些单元格的内容时,我经常收到以下错误消息:

AttributeError: 'NoneType' object has no attribute ‘……’

奇怪的是,我能够将这些单元格放入列表中,并且可以通过这种方式从单元格中读取值:

[… '2005 ', '2006 ', '2007 ', '2008 ', '2009 ', '2010 ', '2011 ', '2012 ', '2013 ', '2014 '….]

但我仍然无法将其与"2015"相提并论。我也无法在每年之后删除空格,因为类型仍然是"NoneType"。

这是我用来查找列号(带有列表的那个)的函数:

def checkvalue(x, y, z):
"""Check if userinput (y) can be found in the row (z), return column number if found"""
print(z)
values = []
for j, cells in enumerate(range(1, x.max_column + 1), 1):
#Cursor
cursor = x.cell(row = z, column = cells)
values.append(cursor.value)
if y in values:
return y
else:
return 999999

我上传了一个数据集作为示例(它是来自欧盟统计局的数据):https://ufile.io/fut70

我的整个脚本(不完整,正在进行中):https://pastebin.com/tdmEynUm

我想知道的是,我该怎么做才能绕过这个"NoneType"问题?我应该重写脚本中的整行吗?或者我应该检查我是否可以用熊猫做点什么?如果我使用y = 2015(末尾有一个空格),那么我可以找到该列。但我不能假设我所有的 excel 文件在最后 100% 的时间都有额外的空间...... 我迷路了。 我意识到这可能是一个非常具体的问题,所以我希望我提供了足够的信息。

非常感谢您的时间

我认为您正在阅读 excel 文件中带有空格的列。 让我们使用以下方法消除该空白区域:

df.columns = df.columns.str.strip()

最新更新