【发布时间】:2018-04-09 17:30:38
【问题描述】:
将私人数据导入 Google Colaboratory 笔记本的常用方法有哪些?是否可以导入非公开的 Google 表格?您无法从系统文件中读取。介绍性文档链接到 guide on using BigQuery,但这似乎有点……很多。
【问题讨论】:
标签: google-sheets google-colaboratory
将私人数据导入 Google Colaboratory 笔记本的常用方法有哪些?是否可以导入非公开的 Google 表格?您无法从系统文件中读取。介绍性文档链接到 guide on using BigQuery,但这似乎有点……很多。
【问题讨论】:
标签: google-sheets google-colaboratory
此处提供了演示本地文件上传/下载以及与 Drive 和工作表集成的官方示例笔记本: https://colab.research.google.com/notebooks/io.ipynb
共享文件的最简单方法是装载您的 Google 云端硬盘。
为此,请在代码单元格中运行以下命令:
from google.colab import drive
drive.mount('/content/drive')
它会要求您访问允许“Google 文件流”的链接以访问您的驱动器。之后将显示一个长的字母数字身份验证代码,需要将其输入到 Colab 的笔记本中。
之后,您的云端硬盘文件将被挂载,您可以使用侧面板中的文件浏览器浏览它们。
【讨论】:
上传
from google.colab import files
files.upload()
下载
files.download('filename')
列出目录
files.os.listdir()
【讨论】:
第 1 步 - 将您的 Google Drive 安装到 Collaboratory
from google.colab import drive
drive.mount('/content/gdrive')
第 2 步 - 现在您将在左侧窗格(文件资源管理器)中看到您的 Google Drive 文件。右键单击需要导入的文件并选择 çopy 路径。 然后像往常一样在 pandas 中导入,使用这个复制的路径。
import pandas as pd
df=pd.read_csv('gdrive/My Drive/data.csv')
完成!
【讨论】:
从您的 googledrive 导入数据的简单方法 - 这样做可以节省人们的时间(不知道为什么 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 中,您可以跳到此步骤。
现在它在您的谷歌驱动器中。在您的谷歌驱动器中找到该文件并右键单击。点击获取“可共享链接”。你会得到一个窗口:
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 文件 - 加载方式取决于文件/数据类型 - .txt、.csv 等):
sample_uploaded_data = json.load(open('sample.json'))
现在您可以打印以查看数据是否存在:
print(sample_uploaded_data)
【讨论】:
google.colab.files.upload() 提出的上传 建议似乎不适用于Firefox 和Safari,仅适用于Chrome。见here
我做的最简单的方法是:
【讨论】:
这允许您通过 Google Drive 上传文件。
运行下面的代码(之前在某个地方找到了这个,但我再也找不到源代码了——感谢编写它的人!):
!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;之后会出现另一个请求访问您的 Google Drive 的权限。
然后,运行它会创建一个名为“drive”的目录,并将您的 Google Drive 链接到它:
!mkdir -p drive
!google-drive-ocamlfuse drive
如果您现在执行!ls,将会有一个目录驱动器,如果您执行!ls drive,您可以看到您Google Drive 的所有内容。
例如,如果我将名为 abc.txt 的文件保存在 Google 云端硬盘中名为 ColabNotebooks 的文件夹中,我现在可以通过路径 drive/ColabNotebooks/abc.txt 访问它
【讨论】:
在任何合作实验室的左侧栏都有一个名为“文件”的部分。 在那里上传您的文件并使用此路径
"/content/YourFileName.extension"
例如:pd.read_csv('/content/Forbes2015.csv');
【讨论】:
pd.read_csv('Forbes2015.csv');
从 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)
【讨论】:
到目前为止,我发现的最适合中小型 CSV 文件的最简单的解决方案是:
pandas.read_csv(URL)时使用复制的URL作为文件地址
这对于逐行读取文本文件或二进制文件可能有效,也可能无效。
【讨论】:
对于那些像我一样来自 Google 的关键字“上传文件 colab”的人:
from google.colab import files
uploaded = files.upload()
【讨论】:
您还可以在https://github.com/ruelj2/Google_drive 上使用我在 google.colab 和 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 Drive 目录中的所有文件,只需
Gd.load_all(local_dir, drive_dir_ID, force=False)
或者只是一个特定的文件
Gd.load_file(local_dir, file_ID)
【讨论】:
正如@Vivek Solanki 所述,我还将我的文件上传到了“文件”部分下的协作仪表板上。
只需记下文件的上传位置即可。为了我,
train_data = pd.read_csv('/fileName.csv') 工作。
【讨论】:
在谷歌 colabs 中 如果这是你第一次,
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")
【讨论】:
您可以通过运行以下命令安装到谷歌驱动器
from google.colab import drive
drive.mount('/content/drive')
之后用于训练将数据从 gdrive 复制到 colab 根文件夹。
!cp -r '/content/drive/My Drive/Project_data' '/content'
第一个路径是 gdrive 路径,第二个是 colab 根文件夹。
这种方式对于大数据的训练速度更快。
【讨论】:
我创建了一小段代码,可以通过多种方式执行此操作。你可以
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()
【讨论】:
已解决,请在此处查找详细信息,请使用以下功能: https://stackoverflow.com/questions/47212852/how-to-import-and-read-a-shelve-or-numpy-file-in-google-colaboratory/49467113#49467113
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!')
【讨论】:
这是将文件从谷歌驱动器导入笔记本的一种方法。
!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}
!mkdir -p drive
!google-drive-ocamlfuse drive
假设您在 Colab_Notebooks 文件夹中的数据集文件,其名称为 db.csv
import pandas as pd
dataset=pd.read_csv("drive/Colab_Notebooks/db.csv")
希望对你有帮助
【讨论】:
如果你想在没有代码的情况下做到这一点,这很容易。 在我的情况下压缩你的文件夹
数据集.zip
然后在 Colab 中右键单击要放置此文件的文件夹,然后按上传并上传此 zip 文件。之后编写这个 Linux 命令。
!unzip <your_zip_file_name>
可以看到你的数据上传成功了。
【讨论】:
如果数据集大小小于 25mb,上传 CSV 文件的最简单方法是从您的 GitHub 存储库。
例子:
import pandas as pd
url = 'copied_raw_data_link'
df1 = pd.read_csv(url)
df1.head()
【讨论】:
使用 Dropbox 的另一种简单方法是:
将您的数据放入保管箱
复制文件的文件共享链接
然后在 colab 中做 wget。
例如: ! wget - O 文件名文件链接(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 collab 的目录,那么这是最简单的方法
【讨论】:
在 Colab 中只需两行代码。非常简单的方法:
!gdown --id 29PGh8XCts3mlMP6zRphvnIcbv27boawn
! unzip file_name.zip
瞧!所有需要的文件都准备好在/content/file_name.csvColab 中使用了
感谢 Gleb Mikhaylov,感谢 Gleb Mikhaylov。
【讨论】: