Skip to main content
 首页 » 编程设计

python之使用 Python 的 xlrd 模块查找日期最多的列

2024年10月25日9sky-heaven

Python(和 StackOverflow!)的新手,如有任何帮助,我们将不胜感激。

我正在尝试遍历 Excel 电子表格中的列,并确定哪一列包含最多的日期条目。

问题似乎与 Excel 电子表格中的格式有关。我的 excel 文件中的日期列为 yyyy-mm-dd,但模块似乎将它们解释为整数,例如2012-10-12 = 1990。同样,日期 3/1/2014 被解释为 3 除以 1 除以 2014 = 0.00149。

到目前为止,我一直在使用 Python 中的 xlrd 模块来计算特定列中的日期数。我试过 .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 之外还有其他方式?

谢谢!

更新:这是文件输入的示例...(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 

我如何构建一个流程来识别 column = 1 是日期数量最多的列(当模块将第 1 列的值解释为整数而不是日期时)

请您参考如下方法:

我认为你在决定它是否是日期时间之前没有查看单元格的类型

 if current_sheet.cell(row,column) == xlrd.XL_CELL_DATE: 

应该改为

 if current_sheet.cell(row,column).ctype == xlrd.XL_CELL_DATE: