举个例子:

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对象上添加DataFrame(表)标题,以便将其输出到由.to_string()生成的字符串中?

推荐答案

  1. DataFrame.style具有与在控制台中打印DataFrame无关的特定用途.代码文档中:

包含用于生成DataFrame的样式化为HTML表示形式的方法.

  1. DataFrame.to_string()many attributes个,但没有一个与显示标题或名称有关.它确实需要header,但这具体涉及到列名.

  2. DataFrame.__repr__使用DataFrame.to_string,所以这里也没有字幕.

总结:not"可以在Pandas DataFrame对象上添加DataFrame(表)标题,这样它就可以以.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'

Python相关问答推荐

从收件箱中的列中删除html格式

运行总计基于多列pandas的分组和总和

从groupby执行计算后创建新的子框架

删除字符串中第一次出现单词后的所有内容

PyQt5,如何使每个对象的 colored颜色 不同?'

Stacked bar chart from billrame

我如何根据前一个连续数字改变一串数字?

使用密钥字典重新配置嵌套字典密钥名

从Windows Python脚本在WSL上运行Linux应用程序

幂集,其中每个元素可以是正或负""""

用两个字符串构建回文

在numpy数组中寻找楼梯状 struct

裁剪数字.nd数组引发-ValueError:无法将空图像写入JPEG

极柱内丢失类型信息""

如果不使用. to_list()[0],我如何从一个pandas DataFrame中获取一个值?

如何在Pandas中用迭代器求一个序列的平均值?

多索引数据帧到标准索引DF

普洛特利express 发布的人口普查数据失败

如何在Polars中将列表中的新列添加到现有的数据帧中?

如何在Django查询集中生成带有值列表的带注释的字段?