【问题标题】:Google spreadsheet to Pandas dataframe via Pydrive without download无需下载即可通过 Pydrive 将 Google 电子表格转换为 Pandas 数据框
【发布时间】:2023-01-18 21:02:19
【问题描述】:

如何在不下载文件的情况下将 Google 电子表格的内容读入 Pandas 数据框?


我认为 gspread 或 df2gspread 可能是不错的选择,但到目前为止我一直在使用 pydrive 并接近解决方案。

使用 Pydrive,我设法获得了我的电子表格的导出链接,作为 .csv 或 .xlsx 文件。在身份验证过程之后,这看起来像


    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    drive = GoogleDrive(gauth)
    
    # choose whether to export csv or xlsx
    data_type = 'csv'
    
    # get list of files in folder as dictionaries
    file_list = drive.ListFile({'q': "'my-folder-ID' in parents and 
    trashed=false"}).GetList()
    
    export_key = 'exportLinks'
    
    excel_key = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    csv_key = 'text/csv'
    
    if data_type == 'excel':
        urls = [ file[export_key][excel_key] for file in file_list ]
    
    elif data_type == 'csv':
        urls = [ file[export_key][csv_key] for file in file_list ]

我为 xlsx 获得的 url 类型是

https://docs.google.com/spreadsheets/export?id=my-id&exportFormat=xlsx

和csv类似

https://docs.google.com/spreadsheets/export?id=my-id&exportFormat=csv

现在,如果我点击这些链接(或使用webbrowser.open(url)访问它们),我下载文件,然后我通常可以使用 pandas.read_excel() 或 pandas.read_csv() 将其读入 Pandas 数据帧,如 here 所述。

如何跳过下载,直接从这些链接将文件读入数据框?

我尝试了几种解决方案:

    pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 2

有趣的是,这些数字 (1, 6, 2) 不依赖于我的电子表格中的行数和列数,这表明该脚本试图读取的内容并非其预期内容。

  • 类似物pd.read_excel(url)给出
    ValueError: Excel file format cannot be determined, you must specify an engine manually.

并指定例如engine = 'openpyxl'给出

zipfile.BadZipFile: File is not a zip file
  • BytesIO 解决方案看起来很有希望,但是

    r = requests.get(url)
    data = r.content
    df = pd.read_csv(BytesIO(data))

仍然给


    pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 6, saw 2

如果我print(data)我得到数百行html代码


    b'\n<!DOCTYPE html>\n<html lang="de">\n  <head>\n  <meta charset="utf-8">\n  <meta content="width=300, initial-scale=1" name="viewport">\n 
    ...
    ...
     </script>\n  </body>\n</html>\n'

【问题讨论】:

    标签: python pandas google-drive-api pydrive


    【解决方案1】:

    在您的情况下,以下修改如何?在这种情况下,通过从gauth 检索访问令牌,将电子表格导出为 XLSX 数据,并将 XLSX 数据放入数据框中。

    修改脚本:

    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()
    
    url = "https://docs.google.com/spreadsheets/export?id={spreadsheetId}&exportFormat=xlsx"
    res = requests.get(url, headers={"Authorization": "Bearer " + gauth.attr['credentials'].access_token})
    values = pd.read_excel(BytesIO(res.content))
    print(values)
    
    • 在此脚本中,请添加import requests。

    • 在这种情况下,使用 XLSX 数据的第一个选项卡。

    • 当您想使用其他标签时,请按如下方式修改values = pd.read_excel(BytesIO(res.content))。

        sheet = "Sheet2"
        values = pd.read_excel(BytesIO(res.content), sheet_name=sheet)
      

    【讨论】:

    • 谢谢!同时,我还可以使用gspread 和pydrive 让它工作。顺便说一句,我很惊喜地找到了你的答案,因为几分钟前你用这个答案让我开心了stackoverflow.com/questions/62358444/…
    • @Davidel 感谢您的回复。很高兴您的问题得到解决。而且,我很高兴我的回答很有用。也谢谢你。
    • @Tanaike 你能回答我的问题吗-stackoverflow.com/questions/71027348/…
    【解决方案2】:

    我想为@Tanaike 的出色回答提供一个额外的选项。确实很难成功地从驱动器和不是google sheet) 到 python 环境中,而不将内容发布到网络上。尽管之前的答案使用 pydrive 和 GoogleAuth(),但我通常在 colab/jupyter 笔记本中使用不同的身份验证方法。改编自googleapis documentation。

    import pandas as pd
    from io import BytesIO
    
    from oauth2client.client import GoogleCredentials
    from google.colab import auth
    auth.authenticate_user()
    
    from google.auth.transport.requests import AuthorizedSession
    from google.auth import default
    creds, _ = default()
    
    spreadsheetId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaa'
    sheetname = 'Sheet12345'
    
    
    xlurl = f'https://docs.google.com/spreadsheets/export?id={spreadsheetId}&exportFormat=xlsx'
    
    authed_session = AuthorizedSession(creds)
    response = authed_session.get(xlurl)
    
    
    values = pd.read_excel(BytesIO(response.content), sheet_name=sheetname)
    values
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      • 2020-07-19
      • 2018-07-22
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      相关资源
      最近更新 更多