繁体   English   中英

如何将 dataframe 从 iPython 复制/粘贴到 Google 表格或 Excel 中?

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

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

我知道如何将结果转换为 csv 并保存。 但是我必须在我的电脑中挖掘,打开结果并将它们粘贴到 Excel 或 Google 表格中。 这需要太多时间。

仅突出显示生成的 dataframe 并复制/粘贴通常会完全弄乱格式,导致列溢出。 (更不用说在 iPython 中打印时长数据帧被截断的问题。)

如何轻松地将 iPython 结果复制/粘贴到电子表格中?

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

如果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

如果您能够使 csv 或 html 可用并且可以通过 url 访问 - 您可以在谷歌表格中使用它。

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

根据我的经验,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']]

这是进一步阐述的基础。 可以使用相同的方法获取字典、namedtuple 等。

在此处输入图像描述

For a small table, you can print the dataframe, use mouse to select the table, copy the table using Ctrl/Cmd + C, go to spreadsheet and paste the table, and you will get the following: 在此处输入图像描述

单击第一个单元格并插入一个单元格以修复 header: 在此处输入图像描述

完毕。

PS:对于更大的表,某些行/列将显示为“...”,请参阅如何扩展 output 显示以查看 Pandas ZBA834BA059A9A379459C112175EB88EZ 的更多列? 显示所有行和列。 对于更大的表(即用鼠标很难select),这种方法就不是那么方便了。

我使用display()而不是print() ,它对我来说很好用。 例子:

from IPython.display import display
import pandas as pd

dict = {'Name' : ['Alice', 'Bob', 'Charlie'],
        'English' : [73, 55, 90],
        'Math' : [78, 100, 33],
        'Geography' : [92, 87, 72]}

df = pd.DataFrame(dict)

display(df)

结果可以很容易地复制并粘贴到 Excel 中,并且不会弄乱格式。 此方法也适用于 Colab。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM