Python脚本无法检索Excel指定月份值,求问题排查
问题
我写了下面这段Python脚本,想在Excel单元格值里检索‘Mar’‘Jun’‘Sep’‘Dec’,然后把匹配到的列名保存到文本文件里,但脚本没返回任何结果。注:脚本只需要检查单元格值,不用处理注释或公式。请问这段脚本有什么问题?
import pandas as pd # Path to the Excel file excel_file = r'E:\Desktop\Big_comp_cap\New Microsoft Excel Worksheet.xlsx' # Read the Excel file df = pd.read_excel(excel_file) # Specify the month names to search for months_to_search = ['Mar', 'Jun', 'Sep', 'Dec'] # Initialize a set to store matching column names matching_columns = set() # Iterate over each cell in the DataFrame for column in df.columns: for index, value in df[column].items(): # Check if the value is a string and contains any of the specified month names if isinstance(value, str): for month in months_to_search: if month in value: matching_columns.add(column) break # Once a match is found, move to the next cell # Write the column names to a text file output_file = 'matching_columns.txt' with open(output_file, 'w') as file: for col_name in matching_columns: file.write(col_name + '\n') print("Matching column names have been saved to:", output_file)
问题分析与修复方案
你的脚本没返回结果,大概率是以下几个原因导致的,对应修复方案如下:
1. 单元格值未被识别为字符串
pandas读取Excel时会自动解析单元格类型,比如显示Mar的日期格式单元格会被转成datetime对象而非字符串;带格式的文本、数字也可能被解析成其他类型。你的脚本只检查isinstance(value, str),会直接跳过这些非字符串单元格。
修复:统一把所有单元格值转成字符串后再检查,消除类型限制。
2. 大小写不匹配
如果Excel里的月份是小写(mar)或全大写(MAR),脚本里的Mar就匹配不到,导致漏判。
修复:把待检查值和目标月份统一转成小写(或大写)后再比较,消除大小写差异。
3. 遍历逻辑冗余且效率低
当前脚本找到一个匹配后,只会跳出月份循环,继续遍历该列的其他单元格——其实只要列里有一个匹配项,就可以直接标记该列并停止遍历此列,没必要继续检查后续单元格。
修复后的脚本(基础版)
import pandas as pd excel_file = r'E:\Desktop\Big_comp_cap\New Microsoft Excel Worksheet.xlsx' df = pd.read_excel(excel_file) months_to_search = ['Mar', 'Jun', 'Sep', 'Dec'] matching_columns = set() for column in df.columns: for value in df[column]: # 统一转成字符串并小写,避免类型和大小写问题 val_str = str(value).lower() for month in months_to_search: if month.lower() in val_str: matching_columns.add(column) # 找到匹配直接跳出所有循环,处理下一列 break else: # 内层循环没找到匹配,继续下一个单元格 continue # 找到匹配,跳出列的遍历循环 break output_file = 'matching_columns.txt' with open(output_file, 'w') as file: for col_name in matching_columns: file.write(col_name + '\n') print("Matching column names have been saved to:", output_file)
更简洁的pandas原生写法
利用pandas的字符串方法可以避免嵌套循环,代码更简洁高效:
import pandas as pd excel_file = r'E:\Desktop\Big_comp_cap\New Microsoft Excel Worksheet.xlsx' df = pd.read_excel(excel_file) months_to_search = ['Mar', 'Jun', 'Sep', 'Dec'] # 生成匹配正则,用|连接所有目标月份 match_pattern = '|'.join(months_to_search) # 检查每列是否有符合条件的单元格:转字符串+忽略大小写匹配 matching_cols = df.columns[df.astype(str).apply(lambda col: col.str.contains(match_pattern, case=False)).any()] # 保存结果 with open('matching_columns.txt', 'w') as f: for col in matching_cols: f.write(f"{col}\n") print("Matching column names have been saved to: matching_columns.txt")
内容的提问来源于stack exchange,提问作者Pubg Mobile
相关产品推荐
相关产品推荐

