Movatterモバイル変換


[0]ホーム

URL:


Python Pandas Tutorial

Python Pandas - Clipboard



Copying and pasting data between different applications is a common task in data analysis. In this,clipboard acts as a temporary data buffer that is used to store short-term data and transfer it between different applications like Excel, text editors, and Python scripts. The Pandas library provides easy tools to work with the system clipboard −

  • read_clipboard(): Reads clipboard data and converts it into a Pandas DataFrame.

  • to_clipboard(): Copies a DataFrame to the clipboard for pasting elsewhere.

These methods make it easy to transfer data between Pandas data structures and other applications like Excel, text editors, or any tool that supports copy-paste functionality.

In this tutorial, we will learn about how to use the Pandasread_clipboard() andto_clipboard() methods effectively.

Note: If you get thepandas.errors.PyperclipException Error then, you may need to installxclip orxsel modules to enable clipboard functionality. Generally,Windows andmacOS operating systems do not require these modules.

Reading Clipboard Data using read_clipboard()

Thepandas.read_clipboard() method is used to directly import data from your system clipboard into a Pandas DataFrame. This method parses the clipboard data similarly to how CSV data is parsed using thepandas.read_csv() method.

The syntax of thepandas.read_clipboard() method is as follows −

pandas.read_clipboard(sep='\\s+', dtype_backend=<no_default>, **kwargs)

Key parameters,

  • sep: This parameter is used to defines the string delimiter. By default it is set to'\s+', which matches one or more whitespace characters.

  • dtype_backend: This is used for selecting the back-end data type. For example, "numpy_nullable" returns a nullable-dtype-backed DataFrame (default), and "pyarrow" returns a pyarrow-backed nullable ArrowDtype DataFrame (introduced in Pandas 2.0).

  • **kwargs: Additional keyword arguments passed toread_csv() to fine-tune the data reading.

Example

Here is a basic example of using thepandas.read_clipboard() method to generate a DataFrame from the copied data. In this example, we initially created a clipboard data using theto_clipboard() method.

import pandas as pd# Creating a sample DataFramedf = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])# Copy DataFrame to clipboarddf.to_clipboard()# Read data from clipboardclipboard_df = pd.read_clipboard()# Display the DataFrameprint('DataFrame from clipboard:')print(clipboard_df)

When we run above program, it produces following result −

DataFrame from clipboard:
ABC
0123
1456

Reading Tabular Data from Clipboard

When clipboard data includes row and column labels,read_clipboard() automatically detects and converts it into a structured DataFrame.

Example

The following example demonstrates how to use thepandas.read_clipboard() method to generate a DataFrame from the copied tabular data.

First, copy the following data to your clipboard using theCtrl+c (Windows/Linux) orCommand-C (macOS) keyboard shortcut.

C1 C2 C3X 1 2 3Y 4 5 6Z a b c

Then Run the following code −

import pandas as pd# Read clipboard content into a DataFramedf = pd.read_clipboard()print(df)

Following is the output of the above code −

C1C2C3
X123
Y456
Zabc

Reading Non-Tabular Data from Clipboard

When you have a non-tabular data in your clipboard with a specific delimiter, you can use thesep parameter of theread_clipboard() method to read such a type of data into Pandas DataFrame.

Example

Below is an example that demonstrates how to read non-tabular clipboard data into a Pandas DataFrame using thepandas.read_clipboard() method.

Copy the following data to your clipboard, then run the program below −

Python,Pandas,Clipboard,DataFrame
import pandas as pd# Read clipboard content into a DataFramedf = pd.read_clipboard(sep=',',header=None)print(df)

Following is the output of the above code −

0123
0PythonPandasClipboardDataFrame

Writing Data to Clipboard with to_clipboard()

Theto_clipboard() method is used to write the content of a DataFrame or Series object to the system clipboard. This makes it easy to paste data into other applications, such as Excel or text editors.

Following is the syntax of theto_clipboard() method −

DataFrame.to_clipboard(*, excel=True, sep=None, **kwargs)

Parameters

  • excel: It is a boolean parameter, if set toTrue, formats the DataFrame as CSV for easy pasting into Excel. IfFalse, formats the DataFrame as a string representation to the clipboard.

  • sep: Defines the field delimiter. If sep=None, it defaults to a tab (\t) delimiter.

  • **kwargs: Any Additional arguments will be passed to DataFrame.to_csv.

Example

Here is an example of copying a DataFrame to the clipboard using theDataFrame.to_clipboard() and pasting it elsewhere like text editors.

import pandas as pd# Create a DataFramedf = pd.DataFrame({    "C1": [1, 2, 3],     "C2": [4, 5, 6],     "C3": ["a", "b", "c"]}, index=["x", "y", "z"])# Copies the DataFrame to the clipboarddf.to_clipboard(sep=',')print('DataFrame is successfully copied to the clipboard. Please paste it into any text editor or Excel sheet.')

Following is the output of the above code −

DataFrame is successfully copied to the clipboard. Please paste it into any text editor or Excel sheet.,C1,C2,C3x,1,4,ay,2,5,bz,3,6,c
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp