pythonpandasdataframepandas-styles

Pandas dataframe title/caption in plain text to_string output?


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()?


Solution

    1. DataFrame.style has a specific use that does not relate to printing DataFrames in the console. From the code documentation:

    Contains methods for building a styled HTML representation of the DataFrame.

    1. DataFrame.to_string() has many attributes, but none of them relate to displaying a caption or a name. It does take a header, but that relates specifically to the column names.

    2. DataFrame.__repr__ uses DataFrame.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:

    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'