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

Python脚本Excel导出失败:sorted_features未定义的NameError问题

问题分析与解决

错误根源

报错NameError: name 'sorted_features' is not defined的原因很直接:你代码最后尝试调用的变量sorted_features从未被定义过。前面的代码只生成了两个关键变量:

  • features:记录链接的对比结果数据集
  • match_counts:匹配分数的统计结果

修正方案

根据你想要导出的内容,选择以下任意一种修改方式:

1. 导出原始对比结果

如果想直接导出features(即compare.compute()生成的匹配对比数据),把最后两行修改为:

output_file = 'sorted_results.xlsx'
features.to_excel(output_file)

2. 导出按匹配分数排序后的结果

如果确实需要导出排序后的特征数据,先对features按匹配分数排序,再导出:

# 按每行的匹配总分降序排序
sorted_features = features.sort_values(by=features.sum(axis=1), ascending=False)
output_file = 'sorted_results.xlsx'
sorted_features.to_excel(output_file)

3. 导出匹配统计结果

如果想导出match_counts(即你打印的匹配分数分布统计),修改为:

output_file = 'sorted_results.xlsx'
match_counts.to_excel(output_file)

额外说明

因为你已经安装了openpyxl,pandas的to_excel()方法会自动使用它作为引擎,无需额外配置。如果导出的数据集包含多层索引(比如features的索引是两个数据集的ID组合),openpyxl完全支持这种格式的写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 01:35:00