如何将 iPython 中的数据框 copy/paste 转换为 Google 表格或 Excel?

How to copy/paste a dataframe from iPython into Google Sheets or Excel?

我最近一直在使用 iPython(又名 Jupyter)进行数据分析和一些机器学习。但一个令人头疼的问题是将笔记本应用程序(浏览器)的结果复制到 Excel 或 Google 表格中,这样我就可以操纵结果或与不使用 iPython 的人分享它们。

我知道如何将结果转换为 csv 并保存。但后来我不得不翻遍我的电脑,打开结果并将它们粘贴到 Excel 或 Google 表格中。那太花时间了。

并且只是突出显示生成的数据框,copy/pasting 通常会完全弄乱格式,导致列溢出。 (更不用说在 iPython 中打印时生成的长数据帧被截断的问题。)

如何轻松地将 copy/paste 的 iPython 结果放入电子表格中?

如果您能够使 url 可以访问 csv 或 html - 您可以在 google 工作表中使用它。

=IMPORTDATA("url to the csv/html file")

尝试使用 to_clipboard() 方法。例如,对于数据框,df: df.to_clipboard() 会将所述数据框复制到剪贴板。然后您可以将其粘贴到 Excel 或 Google 文档中。

根据我的经验,SpreadSheet 使用制表符 (\t) 分隔单元格,使用换行符 (\n) 分隔行。

假设我写了一个简单的函数来从剪贴板数据转换:

def from_excel_to_list(copy_text):
    """Use it to copy and paste data from SpreadSheet software
    (MS Excel, Libreoffice) and convert to a list
    """
    if isinstance(copy_text, str):
        array = []
        rows = copy_text.split("\n")  # splits rows
        for row in rows:
            if len(row):  # removes empty lines
                array.append(row.split("\t"))
        return array
    else:
        raise TypeError("text must be string")

你可以在Jupiter内部定义函数,这样使用:

用 ctrl-c 复制电子表格,然后调用函数 from_excel_to_list 在双括号 ctrl-v 内粘贴数据

my_excel_converted = from_excel_to_list("""Paste here with ctrl-v the text""")

例子

来自ctrl-c的数据:

N   U   tot
1   18,236  18,236
17  20,37   346,29
5   6,318   31,59

调用函数:

from_excel_to_list("""N U   tot
1   18,236  18,236
17  20,37   346,29
5   6,318   31,59
""")

木星结果:

[['N', 'U', 'tot'],
 ['1', '18,236', '18,236'],
 ['17', '20,37', '346,29'],
 ['5', '6,318', '31,59']]

这是进一步阐述的基础。 同样的方法可以获取dictionary、namedtuple等。

如果df.to_clipboard 不起作用。这会起作用。

import io
with io.StringIO() as buffer:
    df.to_csv(buffer, sep=' ', index=False)
    print(buffer.getvalue())

然后,您可以复制打印的数据框并将其粘贴到 Excel 或 Google 表格中。

将输出粘贴到 Atom 之类的 IDE,然后粘贴到 Google Sheets/Excel

对于小的table,你可以打印dataframe,使用鼠标select到table,使用Ctrl/Cmd + C复制table ,转到电子表格并粘贴 table,您将得到以下内容:

单击第一个单元格并插入一个单元格以修复 header:

完成。

PS:对于更大的table,有些rows/columns会显示为'...',参考How do I expand the output display to see more columns of a Pandas DataFrame?显示所有行和列。对于更大的table(用鼠标很难select),这个方法就不太方便了。