如何从 Google Colaboratory 将数据框复制到我的剪贴板(或解决方法)?

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

我正在 google colaboratory 上为非技术用户构建网络抓取工具,并希望 pandas 数据帧形式的抓取工具输出为 "copy pastable" 使用单个内联命令。

执行df.to_clipboard()导致以下错误:

/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...

找到答案了!

不直观,但位于 Google 的 Colab 文档中:

from google.colab import files

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

files.download('example.csv')