确保Python
已安装依赖项:pandas
和openpyxl
pip install pandas openpyxl
把以下代码保存为calc_option_counts.py文件
:
import pandas as pd # 输入文件路径和输出文件路径 input_file = r"C:\Users\XXX\Downloads\data.xlsx" output_file = r"C:\Users\XXX\Downloads\updated_data.xlsx" # 指定工作表名称(可根据需要修改) sheet_name = "Sheet1" # 读取 Excel 文件的指定工作表 try: df = pd.read_excel(input_file, sheet_name=sheet_name) except ValueError as e: print(f"错误:工作表 '{sheet_name}' 不存在。请检查 Excel 文件中的工作表名称。") exit(1) except FileNotFoundError: print(f"错误:文件 {input_file} 未找到。") exit(1) # 确保 Counts 列存在 if 'Counts' not in df.columns: df['Counts'] = '' # 计算每个 Handle 的非空 Option1 Value 行数 handle_counts = df[df['Option1 Value'].notna()].groupby('Handle').size().to_dict() # 确保每个 Handle 都有 Counts(即使 Option1 Value 全为空,Counts 为 0) for handle in df['Handle'].unique(): if handle not in handle_counts: handle_counts[handle] = 0 # 跟踪已处理的 Handle processed_handles = set() # 遍历 DataFrame,设置 Counts for index, row in df.iterrows(): handle = row['Handle'] if handle not in processed_handles: # 第一次出现,设置 Counts df.at[index, 'Counts'] = handle_counts[handle] processed_handles.add(handle) # 保存更新后的 Excel df.to_excel(output_file, index=False) print(f"处理完成,更新后的文件已保存至: {output_file}")