当前位置:迷你笔记 » 技术 » 用Python为Excel每个Handle对应的非空Image Src分配连续的Image Position

用Python为Excel每个Handle对应的非空Image Src分配连续的Image Position

确保Python已安装依赖项:pandasopenpyxl

pip install pandas openpyxl

把以下代码保存为assign_image_position.py文件

import pandas as pd

def assign_image_position(file_path, sheet_name, output_file=None):
    """
    为 Excel 文件中每个 Handle 组的非空 Image Src 分配连续的 Image Position(1, 2, 3...)。
    
    参数:
        file_path (str): 输入 Excel 文件路径
        sheet_name (str): 工作表名称
        output_file (str, optional): 输出文件路径,默认为覆盖原文件
    """
    # 读取 Excel 文件
    try:
        df = pd.read_excel(file_path, sheet_name=sheet_name)
    except Exception as e:
        print(f"读取 Excel 文件失败: {e}")
        return
    
    # 检查必要列是否存在
    required_columns = ["Handle", "Image Src", "Image Position"]
    for col in required_columns:
        if col not in df.columns:
            print(f"错误: 列 '{col}' 不存在于工作表 '{sheet_name}' 中")
            print("可用列名:", df.columns.tolist())
            return
    
    # 调试:打印原始数据
    #print("原始数据(前5行):\n", df[required_columns].head(5).to_string())
    
    # 定义空值检测函数
    def is_empty(value):
        if pd.isna(value):  # 检查 NaN/None
            return True
        str_value = str(value).strip()  # 转换为字符串并去除首尾空白
        return str_value == ""  # 仅空字符串或全空白视为“空”
    
    # 为每个 Handle 组分配 Image Position
    df["Image Position"] = pd.NA  # 清空现有 Image Position
    for handle in df["Handle"].unique():
        # 获取当前 Handle 的子集
        handle_mask = df["Handle"] == handle
        handle_df = df[handle_mask]
        
        # 找到非空的 Image Src
        non_empty_indices = handle_df.index[~handle_df["Image Src"].apply(is_empty)]
        
        # 为非空 Image Src 分配 Image Position(1, 2, 3...)
        for i, idx in enumerate(non_empty_indices, 1):
            df.at[idx, "Image Position"] = i
    
    # 调试:打印处理后的数据
    print("处理后数据(前5行):\n", df[required_columns].head(5).to_string())
    print(f"原始行数: {len(df)}")
    print(f"处理后行数: {len(df)}")
    
    # 保存结果
    if output_file is None:
        output_file = file_path
    try:
        df.to_excel(output_file, sheet_name=sheet_name, index=False)
        print(f"处理完成!已为非空 Image Src 分配 Image Position,结果保存到 {output_file}")
    except Exception as e:
        print(f"保存 Excel 文件失败: {e}")

# 示例用法
if __name__ == "__main__":
    file_path = r"C:\Users\XXX\Downloads\XXX.xlsx"  # 输入 Excel 文件路径
    sheet_name = "Sheet1"  # 工作表名称
    output_file = r"C:\Users\XXX\Downloads\position_output.xlsx"  # 输出文件路径

    assign_image_position(file_path, sheet_name, output_file)
未经允许不得转载:迷你笔记 » 用Python为Excel每个Handle对应的非空Image Src分配连续的Image Position

相关文章

评论 (0)

3 + 1 =