Copying Pandas DataFrame Object Contents To Clipboard

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:

# 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:

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:

# 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:

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

 


Copyright 2023 © pythontic.com