Tengo algunos archivos de datos cargados en mi unidad de Google. Quiero importar esos archivos a google colab.
El método REST API y el método PyDrive muestran cómo crear un nuevo archivo y cargarlo en Drive y Colab. Usando eso, no puedo averiguar cómo leer los archivos de datos que ya están presentes en mi disco en mi código python.
Soy un novato total en esto. ¿Alguien me puede ayudar?
(Actualización del 15 de abril de 2018: el gspread se actualiza con frecuencia, por lo que para garantizar un flujo de trabajo estable, especifico la versión)
Para el archivo de hoja de cálculo, la idea básica es usar los paquetes gspread y pandas para leer hojas de cálculo en Drive y convertirlas al formato de marco de datos de pandas.
En el cuaderno de Colab:
#install packages !pip install gspread==2.1.1 !pip install gspread-dataframe==2.1.0 !pip install pandas==0.22.0 #import packages and authorize connection to Google account: import pandas as pd import gspread from gspread_dataframe import get_as_dataframe, set_with_dataframe from google.colab import auth auth.authenticate_user() # verify your account to read files which you have access to. Make sure you have permission to read the file! from oauth2client.client import GoogleCredentials gc = gspread.authorize(GoogleCredentials.get_application_default())Entonces conozco 3 formas de leer las hojas de cálculo de Google.
Por nombre de archivo:
spreadsheet = gc.open("goal.csv") # Open file using its name. Use this if the file is already anywhere in your drive sheet = spreadsheet.get_worksheet(0) # 0 means the first sheet in the file df2 = pd.DataFrame(sheet.get_all_records()) df2.head()Por URL:
spreadsheet = gc.open_by_url('https://docs.google.com/spreadsheets/d/1LCCzsUTqBEq5pemRNA9EGy62aaeIgye4XxwReYg1Pe4/edit#gid=509368585') # use this when you have the complete url (the edit#gid means permission) sheet = spreadsheet.get_worksheet(0) # 0 means the first sheet in the file df2 = pd.DataFrame(sheet.get_all_records()) df2.head()Por clave de archivo/ID:
spreadsheet = gc.open_by_key('1vpukIbGZfK1IhCLFalBI3JT3aobySanJysv0k5A4oMg') # use this when you have the key (the string in the url following spreadsheet/d/) sheet = spreadsheet.get_worksheet(0) # 0 means the first sheet in the file df2 = pd.DataFrame(sheet.get_all_records()) df2.head()Compartí el código anterior en un cuaderno de Colab: https://drive.google.com/file/d/1cvur-jpIpoEN3vAO8Fd_yVAT5Qgbr4GV/view?usp=sharing
!) Configure sus datos para que estén disponibles públicamente y luego para hojas de cálculo públicas:
from StringIO import StringIO # got moved to io in python3. import requests r = requests.get('https://docs.google.com/spreadsheet/ccc? key=0Ak1ecr7i0wotdGJmTURJRnZLYlV3M2daNTRubTdwTXc&output=csv') data = r.content In [10]: df = pd.read_csv(StringIO(data), index_col=0,parse_dates= ['Quradate']) In [11]: df.head()Más aquí: Obtener CSV de la hoja de cálculo de Google en un marco de datos de Pandas
Si los datos privados son similares, pero tendrá que hacer algunas gimnasias de autenticación...
De fragmentos de Google Colab
from google.colab import auth auth.authenticate_user() import gspread from oauth2client.client import GoogleCredentials gc = gspread.authorize(GoogleCredentials.get_application_default()) worksheet = gc.open('Your spreadsheet name').sheet1 # get_all_values gives a list of rows. rows = worksheet.get_all_values() print(rows) # Convert to a DataFrame and render. import pandas as pd pd.DataFrame.from_records(rows)