From Clipboard to DataFrame with Pandas

When I write about a library or a new concept, I typically like to showcase its working via examples. The source of datasets that I use in my articles varies widely. Sometimes I create simple toy datasets, while on other occasions, I go with the established dataset sites like Kaggle and Google search. However, every time I need to showcase a concept, I have to go through the laborious work of copying the data from the source, saving it to my system, and finally using it in my development environment. Imagine my surprise when I discovered a built-in method in pandas created to address this issue. This method, aptly named as read_clipboard is an absolute savior when you want to try out some new function or library quickly, and in this article, we’ll learn how to use it.

Using pandas.read_clipboard() function

The read_clipboard() method of pandas creates a dataframe from data copied to the clipboard. It reads text from the clipboard and passes it to read_csv() which then returns a parsed DataFrame object.

Syntax

pandas.read_clipboard(sep='\\s+', **kwargs)

If you have worked with pandas’ read_csv(), the read_clipboard() method is essentially the same. The only difference is that the source of data in the latter comes from the clipboard buffer instead of a CSV file.

I have you covered incase you want a deep dive into some of the parameters of the read_csv function in pandas.

Usage

Let’s now look at various ways of using this method. The main steps involved are:

Steps involved | Image by Author

1. Copying data from Excel files

We’ll begin by copying some datasets from an excel file. This is the most common scenario encountered.

Copying data to clipboard | Image by Author

Now the data has been copied onto the clipboard. Next, we will navigate to a Jupyter Notebook(or any IDE) instance and type in the following code snippet:

import pandas as pd
df = pd.read_clipboard()
df
Exit mobile version