excel-toolkit/script_templates/column_calc.py

89 lines
3.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
列计算模板
对列进行加减乘除等计算操作
"""
import pandas as pd
import sys
from pathlib import Path
def main():
# 参数配置
file_path = "{file}"
output_path = "{output}"
operation = "{operation}" # 操作类型: add/subtract/multiply/divide/custom
# 操作参数
column1 = "{column1}" # 第一列
column2 = "{column2}" # 第二列(可选)
result_column = "{result_column}" # 结果列名
value = {value} # 常数值(可选)
formula = "{formula}" # 自定义公式(可选)
# 读取文件
df = pd.read_excel(file_path)
print(f"原始数据: {{len(df)}}")
# 执行计算
if operation == "add":
if column2:
df[result_column] = df[column1] + df[column2]
print(f"计算: {{column1}} + {{column2}} = {{result_column}}")
else:
df[result_column] = df[column1] + value
print(f"计算: {{column1}} + {{value}} = {{result_column}}")
elif operation == "subtract":
if column2:
df[result_column] = df[column1] - df[column2]
print(f"计算: {{column1}} - {{column2}} = {{result_column}}")
else:
df[result_column] = df[column1] - value
print(f"计算: {{column1}} - {{value}} = {{result_column}}")
elif operation == "multiply":
if column2:
df[result_column] = df[column1] * df[column2]
print(f"计算: {{column1}} × {{column2}} = {{result_column}}")
else:
df[result_column] = df[column1] * value
print(f"计算: {{column1}} × {{value}} = {{result_column}}")
elif operation == "divide":
if column2:
df[result_column] = df[column1] / df[column2]
print(f"计算: {{column1}} ÷ {{column2}} = {{result_column}}")
else:
df[result_column] = df[column1] / value
print(f"计算: {{column1}} ÷ {{value}} = {{result_column}}")
elif operation == "custom" and formula:
# 自定义公式(简单实现)
try:
# 替换列名为实际的 Series
context = {{col: df[col] for col in df.columns}}
df[result_column] = eval(formula, {{'pd': pd}}, context)
print(f"自定义公式: {{formula}} = {{result_column}}")
except Exception as e:
print(f"自定义公式执行失败: {{e}}")
sys.exit(1)
# 保存结果
df.to_excel(output_path, index=False)
print(f"\n计算完成")
print(f"输出文件: {{output_path}}")
# 显示统计信息
if result_column in df.columns:
print(f"\n结果列统计 ({{result_column}}):")
print(f" 最小值: {{df[result_column].min():.2f}}")
print(f" 最大值: {{df[result_column].max():.2f}}")
print(f" 平均值: {{df[result_column].mean():.2f}}")
print(f" 总和: {{df[result_column].sum():.2f}}")
if __name__ == "__main__":
main()