Skip to content

Instantly share code, notes, and snippets.

@LinuxIsCool
Created December 30, 2023 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LinuxIsCool/6720ab29a148cb8a354b3206049e0fae to your computer and use it in GitHub Desktop.
Save LinuxIsCool/6720ab29a148cb8a354b3206049e0fae to your computer and use it in GitHub Desktop.
Print names with your dataframes.

I'm looking for a canonical way of displaying the name property of dataframes when printing or logging.

Here is a module that overrides print with a method that prints dataframes with their names if they have the name property, and prints normally otherwise.

import builtins

import pandas as pd

# Save the original print function
original_print = builtins.print

# Define a new print function
def print(*args, **kwargs):
    """
    Override the default print function such that dataframes are named.
    """
    for arg in args:
        if isinstance(arg, pd.DataFrame) and hasattr(arg, 'name'):
            original_print(f'{arg.name}:')
            original_print(arg, **kwargs)
        else:
            original_print(arg, **kwargs)


if __name__ == '__main__':
    # Example usage
    df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
    df.name = 'MyDataFrame'

    print(df)  # This will print the name of the DataFrame and then the DataFrame itself
    print('Hello, World!')  # This will print normally

Usage:

  1. Add names to your dataframes
  2. Import this print function for printing.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment