使用numpy loadtxt将CSV文件导入Google Colab

7

我想将一个JupyterLab笔记本迁移到Google Colab。在JupyterLab中,当我有笔记本文件和相关的csv文件在同一个目录中时,可以通过numpy的loadtxt函数轻松导入数据,如下所示:

import numpy as np
filein = "testfile.csv"
data = np.loadtxt(open(filein, "rb"), delimiter=",", skiprows=1)

出于种种原因,我想在Colab继续使用np.loadtxt。然而,尽管该csv文件与笔记本文件位于同一Google Drive位置,但当我在那里尝试相同的代码时,它无法找到该csv文件。我收到以下错误: "FileNotFoundError:[Errno 2]无此文件或目录:'testfile.csv'"

我猜我需要以某种方式提供文件路径,但一直没有弄清楚如何做到这一点。是否有任何简单的方法可以使用np.loadtxt?


有趣的是,这种方法在Microsoft Azure Notebook上效果非常好。 - Eric S
尝试运行os.listdir(".")命令,看看你能找到什么。 - Rocky Li
@RockyLi 我得到了 ['.config', 'sample_data'] 作为结果。我在笔记本所在的Google Drive文件夹中没有看到这些文件,因此它必须在其他目录中运行。 - Eric S
os.getcwd()输出什么?testfile.csv的目录是什么? - Liam
当我在笔记本中输入os.getcwd()时,我得到:'/content'。我已经将文件testfile.csv放置在与Jupyter笔记本文件相同的目录中,该目录位于我的Google驱动器上:我的驱动器> Colab笔记本 - Eric S
3个回答

11

Colab不会自动挂载Google Drive。默认情况下,工作目录位于短暂的后端虚拟机上的/content

要访问驱动器中的文件,您需要首先使用以下代码段将其挂载:

from google.colab import drive
drive.mount('/content/gdrive')

然后,%cd /content/gdrive/My\ Drive用于将工作目录更改为您的Drive根目录。(或者根据需要自定义路径到testfile.csv所在位置。)


谢谢,这可以运行。我差不多了,但是没有执行%cd - Eric S

2

更简洁,无需命令

# mount gdrive with this code
from google.colab import drive
drive.mount('/content/drive')
#below where the file is in gdrive, change with your
data_path = "/content/drive/My Drive/Colab Notebooks/test/"
yearsBase, meanBase = np.loadtxt(data_path + 'file.csv', delimiter=',', unpack=True)

完成,无需其他代码。再见。


它确实要求确认。 - Nando

1
这里有另一种方式,需要更少的手动干预。如果您打算在多个断开的会话中长时间运行colab笔记本电脑,这将更加有用,这样您就不需要每次手动上传文件。
  1. Upload the text file to google drive. Click share and obtain the shareable link. For example, this is an example shareable link for the file iris.csv: https://drive.google.com/file/d/1Llp483f91dAJriuE6PanmecLA9sWDPyi/view

  2. Copy the file ID from the above link. In this case, it is 1Llp483f91dAJriuE6PanmecLA9sWDPyi

  3. Now you can download the file using the below cell in any colab notebook:

    file_id = "1Llp483f91dAJriuE6PanmecLA9sWDPyi" # replace with your ID
    !gdown https://drive.google.com/uc?id={file_id}
    

输入!ls命令可以查看您工作区中的文件。

如需详细的官方指南,请参考此笔记本:https://colab.research.google.com/notebooks/io.ipynb


这很有趣。该文件已永久上传到我的Google驱动器中,因此不必每次都进行上传。我考虑使用Google Colab而不是Microsoft Azure笔记本的原因是我希望笔记本和数据文件仅对特定用户可访问,而不是公开可用。 - Eric S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接