How can I copy a dataframe to my clipboard (or workaround) from Google Colaboratory?
Asked Answered
A

2

0

I'm building a web scraper for a non-technical user on google colaboratory and want the output of that scraper which is in the form of a pandas dataframe to be "copy pastable" with a single inline command.

The execution of df.to_clipboard() results in the following error:

/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in to_clipboard(self, excel, sep, **kwargs)
   2827         from pandas.io import clipboards
   2828 
-> 2829         clipboards.to_clipboard(self, excel=excel, sep=sep, **kwargs)
   2830 
   2831     def to_xarray(self):

/usr/local/lib/python3.6/dist-packages/pandas/io/clipboards.py in to_clipboard(obj, excel, sep, **kwargs)
    118             text = buf.getvalue()
    119 
--> 120             clipboard_set(text)
    121             return
    122         except TypeError:

/usr/local/lib/python3.6/dist-packages/pandas/io/clipboard/clipboards.py in __call__(self, *args, **kwargs)
    122     class ClipboardUnavailable:
    123         def __call__(self, *args, **kwargs):
--> 124             raise PyperclipException(EXCEPT_MSG)
    125 
    126         def __bool__(self):

PyperclipException: 
PyperclipException: 
    Pyperclip could not find a copy/paste mechanism for your system.
    For more information, please visit https://pyperclip.readthedocs.org 

My Q is similar to this question: pandas.read_clipboard from cloud-hosted jupyter? Though my Q applies to Google's Colab – I suspect there's a built in workaround...

Alastair answered 4/11, 2019 at 5:9 Comment(0)
A
2

Got the answer!

Not intuitive but located in Google's Colab documentation:

from google.colab import files

with open('example.csv', 'w') as f:
  f.write(df.to_csv())

files.download('example.csv')
Alastair answered 4/11, 2019 at 5:25 Comment(0)
S
2

you can use this library: https://github.com/scwilkinson/pd-replicator which implements HTML clipboard API behind a button to constitute as user action

Supportable answered 20/10, 2022 at 15:34 Comment(2)
Link only responses are generally not accepted on SO. But it looks like the solution you posted is helpful. Can you share an example of code of how this would be used, so that this answer doesn't get flagged for anything?Alastair
@YaakovBressler The link follows with a high-level explanation of how the library approaches the issue, so no flagging risk here. I do not have a ready code example but feel free to provide one and edit my answerHousecarl

© 2022 - 2024 — McMap. All rights reserved.