如何将Pandas dataframe的标题/说明以纯文本格式输出到to_string中?

3 投票
2 回答
89 浏览
提问于 2025-04-14 17:24

举个例子:

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) # only works for HTML; https://stackoverflow.com/q/57958432

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() 时就能输出这个标题呢?

2 个回答

3

看起来明确的答案是否定的,因为 to_string 使用的是一个非常简单的 字符串模板,这个模板里没有包含标题。你可以把它和 latexhtml 表格模板 比较一下,这两个模板里是明确包含了标题的。

1
  1. DataFrame.style 是用来给数据表(DataFrame)添加样式的,它跟在控制台里打印数据表没什么关系。根据代码文档的说明:

它包含了构建数据表的样式化HTML表示的方法。

  1. DataFrame.to_string() 有很多属性,但是没有一个是用来显示标题或名称的。它确实有一个 header 属性,但这个属性是专门用来设置列名的。

  2. DataFrame.__repr__ 是使用 DataFrame.to_string 的,所以这里也没有标题。

总结一下:在 Pandas 的数据表对象上不可能添加表格标题,这样它就不会出现在 .to_string() 生成的字符串里。


当然,你可以自己写一个函数来实现这个功能:

data = {
    "Name": ["Alice", "Bob", "Charlie", "David", "Emily"],
    "Age": [25, 30, 35, 40, 45],
    "City": ["New York", "Los Angeles", "Chicago", "Houston", "Boston"],
}

df = pd.DataFrame(data)


def print_df(df, name):
    print(df)
    print(f"{name = }")


print_df(df, name="Example DataFrame")
      Name  Age         City
0    Alice   25     New York
1      Bob   30  Los Angeles
2  Charlie   35      Chicago
3    David   40      Houston
4    Emily   45       Boston
name = 'Example DataFrame'

撰写回答