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

Python使用print输出classification_report时列名偏移如何解决?

classification_report打印列名偏移解决方法

问题原因

打印时将前缀文本和classification_report返回的报告内容拼接在了同一行,而classification_report返回的多行字符串仅第一行的列名前面有对应缩进,后续行都是独立对齐的,前缀占了第一行的开头位置,就会导致第一行列名整体右移,和后续行的内容错开。

解决方法

  • 方法1:加换行符拆分前缀和报告(最简单)
    直接在拼接位置加换行符,让报告全部内容从新行开始对齐,修改代码为:
print('Test classification report :\n' + classification_report(y_test, y_pred))

也可以分开两次打印:

print('Test classification report :')
print(classification_report(y_test, y_pred))
  • 方法2:前缀和第一行报告同列显示
    如果你需要前缀和列名在同一行,给后续所有报告行补上前缀长度的空格即可:
report = classification_report(y_test, y_pred)
prefix = "Test classification report :"
lines = report.split("\n")
# 第一行拼接前缀
lines[0] = prefix + lines[0]
# 后续行补等长空格
for i in range(1, len(lines)):
    lines[i] = " " * len(prefix) + lines[i]
print("\n".join(lines))
  • 方法3:转DataFrame输出(更美观可控)
    调用classification_report时指定output_dict=True将结果转成字典,再用pandas格式化输出,对齐更稳定,还能自定义小数位数:
import pandas as pd
# 生成字典格式的报告
report_dict = classification_report(y_test, y_pred, output_dict=True)
report_df = pd.DataFrame(report_dict).T
print("Test classification report :")
print(report_df.round(2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:39:03