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

Question:

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…

Asked By: Yaakov Bressler

||

Answers:

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')
Answered By: Yaakov Bressler

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

Answered By: o17t H1H' S'k