Colab pydrive 匯入匯出csv(pandas)

weixin_34249678發表於2018-03-04

想試試谷歌提供的免費計算資源,試試用colab,但是資料從谷歌雲盤與colab不知道如何匯入和匯出,花費一個上午的時間搞出來了。

一、首先建立一個隨便叫什麼的資料夾。

5854570-e074141fca3b76ef.png
image.png

二、上傳資料csv,獲取檔案id

5854570-5ccf9f0db3b1a6df.png
image.png

5854570-cd0f1187a0f88fa7.png
image.png

三、新建ipynb檔案

5854570-d338f76b524839b2.png
image.png

四、讀取csv檔案

# Code to read csv file into colaboratory:
!pip install -U -q PyDrive
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)

#2. Get the file   #在此處吧你的檔案id改進去
downloaded = drive.CreateFile({'id':'yourfileID'}) # replace the id with id of file you want to access
#輸入你的檔名字
downloaded.GetContentFile('sample_submission (3).csv')  

#3. Read file as panda dataframe
import pandas as pd
xyz = pd.read_csv('sample_submission (3).csv') 

然後會出現這個介面

5854570-58a77e6af48a7bc6.png
image.png

點連結進去,一路允許,然後複製你得到的code,複製進去回車。

ok,檔案已經匯入進去了。

5854570-6ddd1bc251071b82.png
image.png

五、寫入到谷歌雲盤

xyz.to_csv('over.csv')
#儲存檔案
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# Authenticate and create the PyDrive client.
# This only needs to be done once in a notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# Create & upload a text file.
#你想要匯出的檔案的名字
uploaded = drive.CreateFile({'title': 'OK.csv'})
#改為之前生成檔案的名字
uploaded.SetContentFile('over.csv')
uploaded.Upload()
print('Uploaded file with ID {}'.format(uploaded.get('id')))

檔案就出現在了google雲盤裡了,OK.csv

5854570-b2cc06fedefc1115.png
image.png

相關文章