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

如何将DataFrame对齐列后打印至日志文件?

解决DataFrame日志输出列对齐问题

方法1:用Pandas自带的to_string()方法

这是最省事的原生方案,Pandas的DataFrame内置了格式化输出方法,to_string()会自动计算每列的宽度并对齐,还能自定义数据格式。

替换你原有的代码:

logging.error(f'Quality Metrics for Reconstructed File are Lower than Reference!!!')

# 将DataFrame转为对齐的格式化字符串
formatted_df = df_res.to_string(index=False, float_format='%.2f')
logging.error(formatted_df)
  • index=False:移除行索引,避免日志中出现无关的索引列
  • float_format='%.2f':统一浮点数据保留两位小数,让格式更规整

日志输出会变成对齐的样式:

2022-08-24 16:03:49,084 [ERROR] Quality Metrics for Reconstructed File are Lower than Reference!!!
2022-08-24 16:03:51,263 [ERROR]  mse_avg  mse_r  mse_g  mse_b  psnr_avg  psnr_r  psnr_g  psnr_b
2022-08-24 16:03:51,263 [ERROR]    0.02    0.01    0.03    0.01     65.44    67.82    62.78    67.82

方法2:用tabulate库(更灵活的表格格式)

如果需要更丰富的格式控制(比如自定义对齐方式、分隔线),可以用tabulate库,先安装依赖:

pip install tabulate

然后在代码中使用:

from tabulate import tabulate

logging.error(f'Quality Metrics for Reconstructed File are Lower than Reference!!!')

# 生成对齐的纯文本表格字符串
table_str = tabulate(df_res, headers='keys', tablefmt='plain', floatfmt='.2f', showindex=False)
logging.error(table_str)
  • headers='keys':用DataFrame的列名作为表头
  • tablefmt='plain':采用无分隔线的纯文本格式,适配日志场景
  • floatfmt='.2f':统一浮点数据的显示精度

原方法对齐失败的原因

你之前用固定数量的空格拼接字符串,但列名和数据的长度不一致(比如psnr_avg比mse_avg长,65.44比0.02长),固定空格无法自动适配每列的最大宽度,自然没法对齐。上面两种方法都会自动计算每列的宽度并分配对应空间,因此能实现完美对齐。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:15:39