在 colaboratory 中从驱动器加载 xlsx 文件

Load xlsx file from drive in colaboratory

如何将 MS-excel(.xlsx) 文件从 google 驱动器导入 colaboratory?

excel_file = drive.CreateFile({'id':'some id'})

有效(drive 是一个 pydrive.drive.GoogleDrive 对象)。但是,

print excel_file.FetchContent()

returnsNone。并且

excel_file.content()

投掷:

TypeErrorTraceback (most recent call last) in () ----> 1 excel_file.content()

TypeError: '_io.BytesIO' object is not callable

我的意图是(给定一些有效文件 'id')将其导入为一个 io 对象,它可以被 pandas read_excel() 读取,最后得到一个 pandas 数据帧。

您需要使用 excel_file.GetContentFile 在本地保存文件。然后,你可以在 !pip install -q xlrd.

之后使用 Pandas read_excel 方法

这是一个完整的例子: https://colab.research.google.com/notebook#fileId=1SU176zTQvhflodEzuiacNrzxFQ6fWeWC

我更详细地做了什么:

我创建了一个新的 spreadsheet in sheets 导出为 .xlsx 文件。

接下来,我将其导出为 .xlsx 文件并再次上传到云端硬盘。 URL 是: https://drive.google.com/open?id=1Sv4ib5i7CKWhAHZkKg-uitIkS3xwxtXM

记下文件 ID。在我的例子中是 1Sv4ib5i7CKWhAHZkKg-uitIkS3xwxtXM.

然后,在 Colab 中,我调整了 Drive download snippet 以下载文件。关键位是:

file_id = '1Sv4ib5i7CKWhAHZkKg-uitIkS3xwxtXM'
downloaded = drive.CreateFile({'id': file_id})
downloaded.GetContentFile('exported.xlsx')

最后,创建一个 Pandas DataFrame:

!pip install -q xlrd
import pandas as pd
df = pd.read_excel('exported.xlsx')
df

!pip install... 行安装读取 Excel 个文件所需的 xlrd 库。

也许更简单的方法:

#To read/write data from Google Drive:
#Reference: https://colab.research.google.com/notebooks/io.ipynb#scrollTo=u22w3BFiOveAå
from google.colab import drive
drive.mount('/content/drive')

df = pd.read_excel('/content/drive/My Drive/folder_name/file_name.xlsx')

# #When done, 
# drive.flush_and_unmount()
# print('All changes made in this colab session should now be visible in Drive.')

首先,我从 google.colab

import io
import pandas as pd
from google.colab import files

然后我使用上传小部件上传文件

uploaded = files.upload()

您将得到与此类似的内容(单击“选择文件”并上传 xlsx 文件):

假设文件名是my_spreadsheet.xlsx,那么你需要在下面一行中使用它:

df = pd.read_excel(io.BytesIO(uploaded.get('my_spreadsheet.xlsx')))

就是这样,现在您在 df 数据框中有了第一个 sheet。但是,如果您有多个 sheet,您可以将代码更改为:

首先,将 io 调用移动到另一个变量

xlsx_file = io.BytesIO(uploaded.get('my_spreadsheet.xlsx'))

然后,使用新变量指定 sheet 名称,如下所示:

df_first_sheet = pd.read_excel(xlsx_file, 'My First Sheet')
df_second_sheet = pd.read_excel(xlsx_file, 'My Second Sheet')
import pandas as pd

xlsx_link = 'https://docs.google.com/spreadsheets/d/1Sv4ib5i7CKWhAHZkKg-uitIkS3xwxtXM/export'
df = pd.read_excel(xlsx_link)

如果 xlsx 托管在 Google 驱动器上,一旦共享,任何人都可以使用 link 访问它,有或没有 google 帐户。 google.colab.drivegoogle.colab.files 依赖项不是必需的

到目前为止我找到的最简单的方法。

与我们在桌面上所做的非常相似。

考虑到您已将文件上传到您的 Google 云端硬盘文件夹:

  • 在左侧栏中单击“文件”(在 {x} 下方)
  • Select 挂载驱动程序 > 驱动器 > 文件夹 > 文件(左键单击并复制路径)

之后只需转到代码并通过路径

pd.read_excel('/content/drive/MyDrive/Colab Notebooks/token_rating.xlsx')