簡體   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