What is to_clipboard() in pandas?
Overview
The to_clipboard() function copies objects to our system’s clipboard. It translates the object into its text representation and copies it to the clipboard. You can then paste the converted text into an excel sheet or Notepad++.
Syntax
DataFrame.to_clipboard(excel=True, sep=None, **kwargs)
Parameters
excel: This is boolean, and the default value isTrue. This parameter produces the output in a CSV format and makes it easier to paste into excel.Trueindicates the use of the provided default separator for CSV pasting.Falseindicates that write a string to the clipboard representing the object.sep: This is the separator with the default value,'\t'. This means that the data is separated by a tab. It serves as a field delimiter which means we can indicate the ending and start of the data here. It can be a string, a comma, or any other character.**kwargs: This is a special keyword that allows us to take a variable-length argument. Then, these parameters will be sent to theDataFrame.to_csv().
Return value
None: It does not return any value.
Code
# import pandas library in program
import pandas as pd
import numpy as np
import tkinter as tk
root = tk.Tk()
# create a python dictionary
dictionary = {
'Name': ['Microsoft', 'Google', 'Tesla',\
'Apple.', 'Netflix'],
'Abre': ['MSFT', 'GOOG', 'TSLA', 'AAPL', 'NFLX'],
'Industry': ['Technology', 'Technology', 'Automotive', 'Technology', 'Entertainment'],
'Shares': [50, 500, 150, 200, 80]
}
# create dataframe
df = pd.DataFrame(dictionary)
# print dataframe
print(df)
df.to_clipboard()
df.to_clipboard(sep=',')
# reading the data from your clipboard
data = pd.read_clipboard()
# show data in GUI
label = tk.Label(root,text=data)
label.pack()
root.mainloop()Explanation
- Line 2: We import the pandas package as
pd. This alias will be used to work with the DataFrame. - Line 3–4: We import NumPy and Tkinter into the program.
- Line 5:
root = tk.Tk()creates a graphical user interface (GUI) for the root window. - Line 7–13: We create a data dictionary with some values. Here we use some industry names and their shares.
- Line 15: We create a DataFrame named
df. - Line 17: We display the DataFrame by invoking
print(df). - Line 18: We call
df.to_clipboard()to copy the entire DataFrame to the clipboard. - Line 19: We copy the data to the clipboard while separating them with a comma. By default, the data is separated by a tab (
'\t'). - Line 21:
pd.read_clipboard()reads data from the clipboard. - Line 23–25: These lines copy data to the GUI of the output tab and keep showing on the console.