Copying pandas DataFrame object contents to clipboard

Clipboard provides a short-term storage between programs. Portions of text, images, complete files, folders and much more entities are available at clipboard when they are copied. The to_clipboard() method of the pandas DataFrame copies the contents of a DataFrame instance to clipboard.

Serialization Updated 17 Dec 2019 1 min read

Overview

  • A clipboard in an operating system is a portion of physical memory that provides short-term storage to be used between programs.
  • The clipboard in an operating system enables cut-copy-paste operations between programs and within a program as well.
  • The contents of a pandas DataFrame object can be stored in clipboard through the method to_clipboard().

Example - Copy pandas DataFrame to clipboard in CSV format

python
# Example Python program that copies the contents of a

            # pandas DataFrame instance to the Operating System clipboard

import pandas

            import pyperclip

# Data

            textMatrix = [("Earth", "Sphere", "Geoid"),

                          ("Matter", "Particle", "Wave"),

                          ("Magnet", "Flux", "Electricity")];

# Create a DataFrame

            df = pandas.DataFrame(data=textMatrix);

# Copy DataFrame contents to clipboard in CSV format

            df.to_clipboard(sep=",");

            print("DataFrame as CSV printed from clipboard:");

            print(pyperclip.paste());

Output

Output
DataFrame as CSV printed from clipboard:

,0,1,2

0,Earth,Sphere,Geoid

1,Matter,Particle,Wave

2,Magnet,Flux,Electricity

Example - Copy the string representation of a pandas DataFrame to clipboard

python
# Example Python program that prints the

            # string representation of a pandas DataFrame

            # from the clipboard

            import pandas as pds

            import pyperclip

creditMatrix = [("A", "AA", "A"),

                            ("A", "BBB", "AAA"),

                            ("A", "BB", "AA")];

            df = pds.DataFrame(data=creditMatrix);

            print("DataFrame:");

            print(df);

# Send the DataFrame to system clipboard

            df.to_clipboard(excel=False);

            print("String representation of the DataFrame from the clipboard:");

            print(pyperclip.paste());

Output

Output
DataFrame:

   0    1    2

0  A   AA    A

1  A  BBB  AAA

2  A   BB   AA

String representation of the DataFrame from the clipboard:

   0    1    2

0  A   AA    A

1  A  BBB  AAA

2  A   BB   AA