<p>(2018年4月15日更新:gspread经常更新,因此为了确保稳定的工作流,我指定了版本)</p>
<p>对于电子表格文件,基本思想是使用gspread和pandas包读取驱动器中的电子表格并将其转换为pandas数据帧格式。</p>
<p>在Colab笔记本中:</p>
<pre><code>#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())
</code></pre>
<p>然后我知道三种阅读谷歌电子表格的方法。</p>
<p>按文件名:</p>
<pre><code>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()
</code></pre>
<p>按url:</p>
<pre><code> 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()
</code></pre>
<p>按文件密钥/ID:</p>
<pre><code>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()
</code></pre>
<p>我在Colab笔记本上分享了上面的代码:
<a href="https://drive.google.com/file/d/1cvur-jpIpoEN3vAO8Fd_yVAT5Qgbr4GV/view?usp=sharing" rel="noreferrer">https://drive.google.com/file/d/1cvur-jpIpoEN3vAO8Fd_yVAT5Qgbr4GV/view?usp=sharing</a></p>
<p>来源:<a href="https://github.com/burnash/gspread" rel="noreferrer">https://github.com/burnash/gspread</a></p>