举个例子:
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()
生成的字符串中?