Load Data From the Clipboard
Let’s assume you have an excel sheet containing data you want to process in pandas, but you don’t want to save the file and read the data directly from the file.
Instead, you’d like to simply copy the data structure to your clipboard and let pandas read it from there.
Luckily, pandas has a built-in function for that.
In this lesson you’ll learn how to use pandas’ read_clipboard()
function to read data directly from your clipboard.
00:00 Now it’s time to learn how to take data from the clipboard and get it into Pandas. Pretty often, you’ll need to transfer data from somewhere like Excel or a text editor into a Pandas data structure.
00:10 Sometimes you’ll want to do this without saving the file and then reading that file into Pandas. You might be surprised to find out that Pandas has a method to read data from the clipboard.
00:21 I definitely was, as this was something I had never looked for and didn’t realize I needed until I started using it. So let’s see how this works. Open up a terminal,
00:32
start your Python interpreter, and import pandas as pd
. I’ve gone ahead and opened up an Excel file over here that just has four columns—some integers, some float values, something that may be interpreted as numbers, maybe not, and something that we’re going to want to parse as datetimes.
00:53 So, all I have to do is highlight this, Command + C or Control + C, depending on your operating system. And before I go back, note that this hasn’t been saved.
01:02 This file is only open in memory.
01:07
Head back to the interpreter, make a new DataFrame called df
, and just do pd.read_clipboard()
.
01:17
I want to pass in some arguments, so the na_values
you’ll want to set as a list of [None]
, and parse_dates
, that 'd'
column that had dates.
01:31
Go ahead and run this. And if you take a look at that DataFrame, you should see what was over in Excel. Pandas went ahead and parsed these dates here to datetimes, and if we take a look at the .dtypes
(data types) in this DataFrame, you can see that it knew that the first column was integers, then floats.
01:50 It actually read this as floats, and because it parsed these into dates, it knew they were dates. So that’s pretty cool! It’s a real simple method for pulling structured data off your clipboard.
02:00 And like I said, it’s an example of something that I never would have gone looking for. This is a great reason to skim through documentation for different libraries, because you never know what you’re going to stumble on. And that’s it!
Become a Member to join the conversation.
Matt Williams on Aug. 18, 2020
Well this is a really cool feature.