As an example:
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)
... outputs:
Hello World And Some More
0 1 10.00
1 2 20.00
2 3 30.00
3 4 40.00
... and clearly, there is no table title/caption in the plain text output of .to_string().
Sure I can just print(df_caption) myself separately - but is it otherwise somehow possible to add dataframe (table) caption on the Pandas DataFrame object, so that it is output in the string generated by .to_string()?
DataFrame.stylehas a specific use that does not relate to printing DataFrames in the console. From the code documentation:DataFrame.to_string()has many attributes, but none of them relate to displaying a caption or a name. It does take aheader, but that relates specifically to the column names.DataFrame.__repr__usesDataFrame.to_string, so no captions here either.In conclusion: it's not "possible to add dataframe (table) caption on the Pandas DataFrame object, so that it is output in the string generated by
.to_string()".You can, of course, create your own function to do that: