将数据导入 Google Colaboratory

Import data into Google Colaboratory

将私有数据导入 Google Colaboratory notebooks 的常用方法有哪些?是否可以导入非public Google sheet?您无法读取系统文件。介绍性文档 link 到 guide on using BigQuery,但这似乎有点......很多。

演示本地文件 upload/download 以及与云端硬盘和工作表集成的官方示例笔记本可在此处获得: https://colab.research.google.com/notebooks/io.ipynb

共享文件的最简单方法是装载 Google 驱动器。

为此,运行 代码单元格中的以下内容:

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

它会要求您访问 link 以允许 "Google Files Stream" 访问您的驱动器。之后将显示一长串字母数字授权代码,需要将其输入到您的 Colab 笔记本中。

之后,您的云端硬盘文件将被装载,您可以使用侧面板中的文件浏览器浏览它们。

这是一个full example notebook

我做的最简单的方法是:

  1. 使用您的数据集在 github 上创建存储库
  2. 使用 ! git clone --recursive [GITHUB LINK REPO]
  3. 查找您的数据在哪里(!ls 命令)
  4. 像在普通 jupyter notebook 中那样使用 pandas 打开文件。

目前为止我找到的最简单的解决方案非常适合 mid-size CSV 文件:

  1. 在 gist.github.com 上创建秘密要点并上传(或 copy-paste 文件的内容)。
  2. 单击 Raw 查看并复制原始文件 URL。
  3. 调用时使用复制的URL作为文件地址pandas.read_csv(URL)

这对于逐行读取文本文件或二进制文件可能有效,也可能无效。

从您的 google 驱动器导入数据的简单方法 - 这样做可以节省人们的时间(不知道为什么 google 只是没有明确地列出这一步)。

安装并验证 PYDRIVE

     !pip install -U -q PyDrive ## you will have install for every colab session

     from pydrive.auth import GoogleAuth
     from pydrive.drive import GoogleDrive
     from google.colab import auth
     from oauth2client.client import GoogleCredentials

     # 1. Authenticate and create the PyDrive client.
     auth.authenticate_user()
     gauth = GoogleAuth()
     gauth.credentials = GoogleCredentials.get_application_default()
     drive = GoogleDrive(gauth)

正在上传

如果需要从本地盘上传数据:

    from google.colab import files

    uploaded = files.upload()

    for fn in uploaded.keys():
       print('User uploaded file "{name}" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))

执行,这将显示一个选择文件按钮 - 找到您的上传文件 - 点击打开

上传后会显示:

    sample_file.json(text/plain) - 11733 bytes, last modified: x/xx/2018 - %100 done
    User uploaded file "sample_file.json" with length 11733 bytes

为笔记本创建文件

如果你的数据文件已经在你的gdrive中,你可以跳到这一步。

现在它在您的 google 驱动器中。在 google 驱动器中找到该文件并右键单击。单击获取 'shareable link.' 您将获得一个 window,其中:

    https://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn

复制 - '29PGh8XCts3mlMP6zRphvnIcbv27boawn' - 这是文件 ID。

在你的笔记本中:

    json_import = drive.CreateFile({'id':'29PGh8XCts3mlMP6zRphvnIcbv27boawn'})

    json_import.GetContentFile('sample.json') - 'sample.json' is the file name that will be accessible in the notebook.

将数据导入笔记本

将您上传的数据导入笔记本(本例中为 json 文件 - 加载方式取决于 file/data 类型 - .txt、.csv 等):

    sample_uploaded_data = json.load(open('sample.json'))

现在您可以打印以查看数据是否存在:

    print(sample_uploaded_data)

从 Dropbox 快速轻松地导入:

!pip install dropbox
import dropbox
access_token = 'YOUR_ACCESS_TOKEN_HERE' # https://www.dropbox.com/developers/apps
dbx = dropbox.Dropbox(access_token)

# response = dbx.files_list_folder("")

metadata, res = dbx.files_download('/dataframe.pickle2')

with open('dataframe.pickle2', "wb") as f:
  f.write(res.content)

上传

from google.colab import files
files.upload()

下载

files.download('filename')

列出目录

files.os.listdir()

这允许您通过 Google 云端硬盘上传文件。

运行 下面的代码(之前在某个地方找到了这个,但我再也找不到来源了——归功于写它的人!):

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

单击出现的第一个 link,它会提示您登录 Google;之后会出现另一个请求访问您的 Google 驱动器的权限。

然后,运行 这将创建一个名为 'drive' 的目录,并且 link 将您的 Google 驱动到它:

!mkdir -p drive
!google-drive-ocamlfuse drive

如果你现在做一个!ls,会有一个目录驱动器,如果你做一个!ls drive,你可以看到你的Google驱动器的所有内容。

例如,如果我将名为 abc.txt 的文件保存在 Google 驱动器中名为 ColabNotebooks 的文件夹中,我现在可以通过路径 drive/ColabNotebooks/abc.txt

已解决,详情请看这里,请使用以下功能:

from google.colab import files
import zipfile, io, os

    def read_dir_file(case_f):
        # author: yasser mustafa, 21 March 2018  
        # case_f = 0 for uploading one File and case_f = 1 for uploading one Zipped Directory
        uploaded = files.upload()    # to upload a Full Directory, please Zip it first (use WinZip)
        for fn in uploaded.keys():
            name = fn  #.encode('utf-8')
            #print('\nfile after encode', name)
            #name = io.BytesIO(uploaded[name])
        if case_f == 0:    # case of uploading 'One File only'
            print('\n file name: ', name)
            return name
        else:   # case of uploading a directory and its subdirectories and files
            zfile = zipfile.ZipFile(name, 'r')   # unzip the directory 
            zfile.extractall()
            for d in zfile.namelist():   # d = directory
                print('\n main directory name: ', d)
                return d
    print('Done!')

这是将文件从 google 驱动器导入笔记本的一种方法。

打开 jupyter 笔记本和 运行 下面的代码并完成身份验证过程

!apt-get install -y -qq software-properties-common python-software-properties   module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse
from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass
!google-drive-ocamlfuse -headless -id={creds.client_id} -secret=  {creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

完成上述代码后,运行下面的代码将挂载 google 驱动器

!mkdir -p drive
!google-drive-ocamlfuse drive

正在将文件从 google 驱动器导入笔记本(例如:Colab_Notebooks/db.csv)

假设您的数据集文件位于 Colab_Notebooks 文件夹中,其名称为 db.csv

import pandas as pd
dataset=pd.read_csv("drive/Colab_Notebooks/db.csv")

希望对你有帮助

第 1 步 - 将您的 Google 驱动器安装到 Collaboratory

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

第 2 步 - 现在您将在左侧窗格(文件资源管理器)中看到您的 Google 驱动器文件。右键单击您需要导入的文件和 select çopy 路径。 然后像往常一样导入 pandas,使用这个复制的路径。

import pandas as pd
df=pd.read_csv('gdrive/My Drive/data.csv')

完成!

在任何合作实验室的左侧栏上都有一个名为 "Files" 的部分。 在那里上传你的文件并使用这个路径

"/content/YourFileName.extension"

例如:pd.read_csv('/content/Forbes2015.csv');

您还可以在 google.colab 上使用我的实现,在 https://github.com/ruelj2/Google_drive 上使用 PyDrive,这样会更容易。

!pip install - U - q PyDrive  
import os  
os.chdir('/content/')  
!git clone https://github.com/ruelj2/Google_drive.git  

from Google_drive.handle import Google_drive  
Gd = Google_drive()  

然后,如果要加载 Google 驱动器目录中的所有文件,只需

Gd.load_all(local_dir, drive_dir_ID, force=False)  

或者只是一个带有

的特定文件
Gd.load_file(local_dir, file_ID)

如果您想在没有代码的情况下执行此操作,那非常简单。 在我的例子中压缩你的文件夹是

dataset.zip

然后在 Colab 中右键单击要放置此文件的文件夹,然后按“上传”并上传此 zip 文件。之后写这个 Linux 命令。

!unzip <your_zip_file_name>

可以看到你的数据已经上传成功了。

正如@Vivek Solanki 所提到的,我还在 "File" 部分下的协作仪表板上上传了我的文件。 只需记下文件上传的位置。为了我, train_data = pd.read_csv('/fileName.csv') 有效。

如果数据集大小小于 25mb,上传 CSV 文件的最简单方法是从您的 GitHub 存储库。

  1. 单击存储库中的数据集
  2. 单击“查看原始数据”按钮
  3. 复制 link 并将其存储在变量中
  4. 加载变量到Pandas read_csv得到dataframe

示例:

import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()

在 google 协作中 如果这是你第一次,

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

运行 这些代码并通过输出链接 然后通过 pass-prase 到盒子

复制的时候可以复制如下, 转到文件右键单击并复制路径 ***不要忘记删除“/content”

f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")

对于那些像我一样来自 Google 关键字 "upload file colab" 的人:

from google.colab import files
uploaded = files.upload()
  1. 您可以通过运行以下

    挂载到google驱动器

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

  2. 之后为了训练将数据从 gdrive 复制到 colab 根文件夹。

!cp -r '/content/drive/My Drive/Project_data' '/content'

其中第一个路径是 gdrive 路径,第二个路径是 colab 根文件夹。

这种方式对大数据的训练速度更快。

上传数据/将数据导入 Google colab GUI 方式的最佳和简单方法是单击最左侧的第三个选项文件菜单图标,然后您将在 [=15] 中获得上传浏览器文件=] OS 。检查下面的图像更容易 understanding.After 点击下面的两个选项你会得到上传 window 框容易。完工。

from google.colab import files
files=files.upload()

我创建了一小段代码,可以通过多种方式执行此操作。你可以

  1. 使用已经上传的文件(重启内核时有用)
  2. 使用来自Github
  3. 的文件
  4. 手动上传文件
import os.path

filename = "your_file_name.csv"
if os.path.isfile(filename):
  print("File already exists. Will reuse the same ...")
else:
  use_github_data = False  # Set this to True if you want to download from Github
  if use_github_data:
    print("Loading fie from Github ...")
    # Change the link below to the file on the repo
    filename = "https://github.com/ngupta23/repo_name/blob/master/your_file_name.csv" 
  else:
    print("Please upload your file to Colab ...")
    from google.colab import files
    uploaded = files.upload()

另一种使用 Dropbox 的简单方法是:

将您的数据放入保管箱

复制您文件的文件共享link

然后在colab中做wget。

例如: ! wget -O filename filelink(like-https://www.dropbox.com/.....)

大功告成。数据将开始出现在您的 colab 内容文件夹中。

您可以使用以下功能。我假设您正在尝试上传数据框类型的文件(.csv、.xlsx)

def file_upload():
    file = files.upload()
    path = f"/content/{list(file.keys())[0]}"
    df = pd.read_excel(path)
    return df

#your file will be saved in the variable: dataset
dataset = file_upload()

如果您没有更改 google 协作的目录,那么这是最简单的方法

在 Colab 中只需两行代码。非常简单的方法:

  1. 将一个 zip 存档中的所有文件加载到 Google 驱动器。
  2. 通过 link 让每个人都能看到它。
  3. 从这个 link 复制 ID。 (例如:在这个linkhttps://drive.google.com/open?id=29PGh8XCts3mlMP6zRphvnIcbv27boawn中ID是29PGh8XCts3mlMP6zRphvnIcbv27boawn
  4. 在 Colab 中输入: !gdown --id 29PGh8XCts3mlMP6zRphvnIcbv27boawn
  5. 进入 Colab 的最后一步: ! unzip file_name.zip

Voilà! 所有需要的文件都已准备好在 /content/file_name.csv

中的 Colab 中使用

对于这种从云端硬盘到 Colab 的简单方法,我要感谢 Gleb Mikhaylov。