如何将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) # 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 个回答
1
DataFrame.style
是用来给数据表(DataFrame)添加样式的,它跟在控制台里打印数据表没什么关系。根据代码文档的说明:
它包含了构建数据表的样式化HTML表示的方法。
DataFrame.to_string()
有很多属性,但是没有一个是用来显示标题或名称的。它确实有一个header
属性,但这个属性是专门用来设置列名的。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'