Skip to main content
 首页 » 编程设计

Python之单元格类型 'NoneType' 而值在里面。怎么改造呢

2025年01月19日9cyq1162

在过去的几个小时里,我一直在努力解决这个问题。我正在编写一个一次性使用的脚本,我希望它能节省我很多时间。 该脚本的目的如下:

#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. 

我事先使用 pandas 将 .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”问题?我应该重写脚本中的整行吗?或者我应该检查我是否可以用 Pandas 做点什么?如果我使用 y = 2015(末尾有一个空格),那么我可以找到该列。但我不能假设我所有的 excel 文件在 100% 的时间结束时都有额外的空间...... 我搞不清楚了。 我意识到这可能是一个非常具体的问题,所以我希望我已经提供了足够的信息。

非常感谢您的宝贵时间

请您参考如下方法:

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

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