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

Eri*_*ain 3 python import numpy google-colaboratory

我正在尝试将JupyterLab笔记本迁移到Google Colab。在JupyterLab中,当我的笔记本文件和关联的csv文件位于同一目录中时,可以使用numpy的loadtxt函数轻松导入数据,如下所示:

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

由于各种原因,我想继续在Colab中使用np.loadtxt。但是,当我在那里尝试相同的代码时,尽管它与笔记本文件位于相同的Google云端硬盘位置,却找不到csv文件。我收到此错误:"FileNotFoundError: [Errno 2] No such file or directory: 'testfile.csv'"

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

Bob*_*ith 5

Colab doesn't automatically mount Google Drive. By default, the working directory is /content on an ephemeral backend virtual machine.

To access your file in Drive, you'll need to mount it first using the following snippet:

from google.colab import drive
drive.mount('/content/gdrive')
Run Code Online (Sandbox Code Playgroud)

Then, %cd /content/gdrive/My\ Drive to change the working directory to your Drive root. (Or, customize the path as needed to wherever testfile.csv is located.)