使用Python的xlrd模块查找大多数date的列
新的Python(和StackOverflow!),任何帮助将不胜感激。
我试图通过Excel电子表格中的列循环,并确定哪个列包含最高数量的date条目。
问题似乎是在Excel电子表格中进行格式化。 在我的excel文件中的date被列为yyyy-mm-dd,但该模块似乎将它们解释为整数,例如2012-10-12 = 1990。同样,date3/1/2014被解释为3分按1除以2014 = 0.00149。
到目前为止,我一直使用Python中的xlrd模块来计算特定列中date的数量。 我已经尝试使用.xls和.xlsx,并尝试formatting_info = True,但没有成功。
这是我尝试使用的函数的代码…
import xlrd from xlrd import open_workbook from xlrd import XL_CELL_DATE def find_maturity_date_column2(file, threshold): wb = open_workbook(file) sheet_index = 0 max_sheet_score = 0 max_col_score = 0 maturity_sheet_index = 0 maturity_col_index = 0 for a in wb.sheets(): current_sheet = wb.sheet_by_index(sheet_index) sheet_score = 0 for column in range(0,a.ncols): col_score = 0 for row in range(0,a.nrows): if current_sheet.cell(row,column).ctype == xlrd.XL_CELL_DATE: sheet_score = sheet_score + 1 col_score = col_score + 1 else: sheet_score = sheet_score col_score = col_score if sheet_score >= max_sheet_score and col_score > max_col_score: max_col_score = col_score max_sheet_score = sheet_score maturity_sheet_index = sheet_index maturity_col_index = column else: max_col_score = max_col_score max_sheet_score = max_sheet_score maturity_sheet_index = maturity_sheet_index maturity_col_index = maturity_col_index sheet_index = sheet_index + 1 if max_col_score < threshold: maturity_sheet_index = "None Found" maturity_col_index = "None Found" else: maturity_sheet_index = maturity_sheet_index maturity_col_index = maturity_col_index return maturity_sheet_index, maturity_col_index
此代码不会生成任何成功。 任何想法如何我可以解决这个问题? 也许除了xlrd有别的办法吗?
谢谢!
更新:这是一个文件input的例子…(以CSV格式)
Tranche,Maturity Date,Country,Currency,Initial Spread Term Loan B,2020-10-12,USA,USD,0.025 Term Loan B,2020-11-02,USA,USD,0.0275 Term Loan B,2020-05-22,USA,USD,0.0275
我如何构build一个进程来识别该列= 1是具有最高date数的列(当模块将列1值解释为整数而不是date时)
我认为你在决定是否是一个date时间之前,正在寻找单元格的types
if current_sheet.cell(row,column) == xlrd.XL_CELL_DATE:
应该改成
if current_sheet.cell(row,column).ctype == xlrd.XL_CELL_DATE:
我必须在这里打破Stack Overflow协议,并提供一个“答案”,即使这个问题真正需要的是更清晰的评论和编辑(或者更好的聊天室)。 现有的评论意见已经太长了。
怀疑文件中的“date”由于格式不正确而不被xlrd检测为date(即,它们不是date,在任何Excel意义上)是好的。 所以问题是:他们是什么?
我们至less可以从两个angular度来看待这个问题:报告xlrd告诉我们什么,或者报告Excel告诉我们什么。 (是的,还有其他的事情我们可以做,但老实说,xlrd是一个非常有能力的Excel读者,我们不应该使用其他任何东西。)
现在,我确定xlrd不会将任何单元解释为“具有整数输出的公式”。 xlrd并不知道或关心公式,而从数据存储的angular度来说,没有像Excel整数那样的东西。 (Excel中的每个数字都是一个浮点数,有些可能碰巧有一个等于一个整数的值,但是它们的数据types是float,这包括Excel可能会考虑的一个date。
所以,在Excel方面:单元格是什么样的? 截图是一个比CSV更好的支持文档,因为在写入CSV时会丢失大量信息(将CSV加载到Excel中经常会给出与开始时不同的内容)。 什么是单元格的格式string? (从Excel导航菜单,就好像要手动更改格式一样,select“自定义”选项,它应显示现有的格式string,可能类似于0.00
或#,##0.00
或m/d/yyyy
或@
等)
从xld方面来看,有问题的单元格的ctype
和value
是什么? 而不是只打印值,使用repr
函数打印表示。 例如,
print current_sheet.cell(row,column).ctype print repr(current_sheet.cell(row,column).value)
提供这些信息(编辑你的问题或评论这个答案),也许我们会取得一些进展。
顺便说一下,你的代码绝对不是那么简洁。 有很多线路根本就没有做任何事情。 我明白了,你还是新手,那很好。 尽pipe如此,代码在给出的CSV数据上似乎起作用(因为如果您将该CSV加载到Excel中,则会将date看起来的东西解释为date)。