如何为Pandas DataFrame添加标题并在to_string()输出中显示?
问题描述
示例代码:
import pandas as pd df = pd.DataFrame({ "Hello World": [1, 2, 3, 4], "And Some More": [10.0, 20.0, 30.0, 40.0], }) df_caption = "Table 1: My Table" df.style.set_caption(df_caption) # 仅对HTML输出有效 with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'max_colwidth', 50, 'display.float_format', "{:.2f}".format): df_str = df.to_string() print(df_str)
运行输出:
Hello World And Some More 0 1 10.00 1 2 20.00 2 3 30.00 3 4 40.00
显然,to_string()的纯文本输出里不包含表格标题。虽然可以单独执行print(df_caption)输出标题,但能不能直接在Pandas DataFrame对象上添加表格标题,让它在to_string()生成的字符串里一并输出?
解决方案
Pandas没有原生支持给DataFrame绑定标题并让to_string()自动输出的功能,但可以通过以下几种简单方式实现需求:
方法1:手动拼接标题与表格字符串
这是最直接的实现方式,直接把标题和to_string()的结果拼接在一起:
import pandas as pd df = pd.DataFrame({ "Hello World": [1, 2, 3, 4], "And Some More": [10.0, 20.0, 30.0, 40.0], }) df_caption = "Table 1: My Table" with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'max_colwidth', 50, 'display.float_format', "{:.2f}".format): df_str = f"{df_caption}\n{df.to_string()}" print(df_str)
输出结果:
Table 1: My Table Hello World And Some More 0 1 10.00 1 2 20.00 2 3 30.00 3 4 40.00
方法2:给DataFrame添加自定义属性
如果想让标题和DataFrame绑定在一起,可以给对象添加自定义属性,后续拼接时直接调用:
import pandas as pd df = pd.DataFrame({ "Hello World": [1, 2, 3, 4], "And Some More": [10.0, 20.0, 30.0, 40.0], }) df.caption = "Table 1: My Table" # 给DataFrame添加自定义标题属性 with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'max_colwidth', 50, 'display.float_format', "{:.2f}".format): df_str = f"{df.caption}\n{df.to_string()}" print(df_str)
方法3:封装成自定义函数
如果频繁需要这个功能,可以封装成可复用的函数:
import pandas as pd def df_to_string_with_caption(df, caption): with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'max_colwidth', 50, 'display.float_format', "{:.2f}".format): return f"{caption}\n{df.to_string()}" # 使用示例 df = pd.DataFrame({ "Hello World": [1, 2, 3, 4], "And Some More": [10.0, 20.0, 30.0, 40.0], }) print(df_to_string_with_caption(df, "Table 1: My Table"))
内容的提问来源于stack exchange,提问作者sdbbs
相关产品推荐
相关产品推荐

