我正试图将数据帧打印到日志文件中,但列未对齐。我提出了这个解决方案,将数据帧列和行作为列表,然后将列和浮点数据转换为字符串,但必须有更好的方法。
logging.error(f'Quality Metrics for Reconstructed File are Lower than Reference!!!')
print(df.shape)
columns = df_res.columns
msg = ' '.join(columns)
print(msg)
logging.error(msg)
data = df_res.iloc[0,:].tolist()
msg = ' '.join(map(str, data))
print(msg)
logging.error(msg)```
This is what the log file looks like.
2022-08-24 16:03:49,084 [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
You can see that the columns are not aligned correctly. Any advice on a better way to do this so that my log output is properly formatted?
此示例使用str.format
正确格式化列标题和数据帧第一行的值:
max_column_len = len(max(df.columns, key=len))
fmt = "{{:>{}}} ".format(max_column_len) * len(df.columns)
columns = fmt.format(*df.columns)
first_row = fmt.format(*df.iloc[0])
print(columns) # <--- you can use `columns` in your logging function
print(first_row) # <--- ...
打印:
mse_avg mse_r mse_g mse_b psnr_avg psnr_r psnr_g psnr_b
0.02 0.01 0.03 0.01 65.44 67.82 62.78 67.82
使用的数据帧:
mse_avg mse_r mse_g mse_b psnr_avg psnr_r psnr_g psnr_b
0 0.02 0.01 0.03 0.01 65.44 67.82 62.78 67.82
另一种解决方案:
# convert dataframe string and then split it:
for line in str(df).splitlines():
print(line)
您可以使用以下panda方法:
string = df.to_csv(sep='t')
它将用制表器将条目分隔开,制表器在大多数文本编辑器中应该对齐显示。