You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本执行耗时过长且无限循环输出,求问题排查

问题排查与修正:找出同一galaxyID下导致重复的差异列

你的脚本逻辑完全偏离需求,导致输出所有行(看起来像“无限循环”),核心问题有三点:

  • drop_duplicates(keep=False)的作用是删除所有重复行,只保留分组内完全唯一的行,这和你要找“重复行中差异列”的需求完全相反
  • unique_columns直接取所有列索引,根本没计算哪些列是差异源
  • 没有针对“同一galaxyID下重复行”做分析,反而把无关行全部输出

正确实现思路

要找出同一galaxyID下导致重复的列,核心是:对每个galaxyID的分组,找出哪些列的值不是全相同的——这些列就是导致行重复但内容有差异的原因。如果某列在分组内所有行的值都一致,那它肯定不是重复的诱因。


修正后的代码

方案1:仅输出每个galaxyID对应的差异列(简洁版)

import pandas as pd

def find_diff_columns_by_galaxyID(file_path):
    df = pd.read_excel(file_path, engine='openpyxl')
    # 按galaxyID分组,计算每列的唯一值数量
    grouped_unique_counts = df.groupby('galaxyID').nunique()
    
    diff_columns_by_id = {}
    for galaxy_id, row in grouped_unique_counts.iterrows():
        # 筛选出唯一值数量>1的列(即存在差异的列)
        diff_cols = row[row > 1].index.tolist()
        diff_columns_by_id[galaxy_id] = diff_cols
    
    return diff_columns_by_id

if __name__ == "__main__":
    file_path = "astronomy_observation_data.xlsx"
    diff_columns = find_diff_columns_by_galaxyID(file_path)
    
    for galaxy_id, cols in diff_columns.items():
        print(f"galaxyID: {galaxy_id}")
        if cols:
            print(f"导致重复的差异列: {', '.join(cols)}")
        else:
            print("该分组下所有行完全重复,无差异列")
        print("--------------------")

方案2:输出差异列+具体重复行的差异内容(详细版)

如果需要查看重复行的具体差异数据,可以用这个版本:

import pandas as pd

def find_diff_rows_by_galaxyID(file_path):
    df = pd.read_excel(file_path, engine='openpyxl')
    diff_rows_by_id = {}
    
    for galaxy_id, group in df.groupby('galaxyID'):
        # 筛选出分组内重复出现的行(出现次数≥2)
        duplicate_rows = group[group.duplicated(keep=False)]
        if not duplicate_rows.empty:
            # 获取当前分组的差异列
            diff_cols = group.nunique()[group.nunique() > 1].index.tolist()
            diff_rows_by_id[galaxy_id] = {
                'diff_columns': diff_cols,
                'duplicate_row_details': duplicate_rows[diff_cols].to_dict('records')
            }
    
    return diff_rows_by_id

if __name__ == "__main__":
    file_path = "astronomy_observation_data.xlsx"
    diff_data = find_diff_rows_by_galaxyID(file_path)
    
    for galaxy_id, data in diff_data.items():
        print(f"galaxyID: {galaxy_id}")
        print(f"差异列: {', '.join(data['diff_columns'])}")
        print("重复行的差异内容:")
        for row in data['duplicate_row_details']:
            print(row)
        print("--------------------")

内容的提问来源于stack exchange,提问作者SkyeBoniwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:35:52