【问题标题】:Get CSV from google drive and then load to pandas从谷歌驱动器获取 CSV,然后加载到熊猫
【发布时间】:2021-01-04 21:27:18
【问题描述】:

我的目标是从谷歌驱动器读取 .csv 文件并将其加载到数据帧。

我尝试了一些答案 here 但问题是,该文件不是公开的,需要身份验证。

我查看了护目镜驱动 API,但我被困在那里,我不知道如何前进。我确实设法打开了 google sheet 并将其加载到数据框中,但这是不同的,这是一个适用于 google sheet 的示例。

service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
sheets_file = sheet.values().get(
                     spreadsheetId=sheet_id,
                     range=sheet_range
                     ).execute()
    
header = sheets_file.get('values', [])[0]   # Assumes first line is header!
values = sheets_file.get('values', [])[1:]  # Everything else is data.
  
if not values:
    print('No data found.')
else:
    all_data = []
    for col_id, col_name in enumerate(header):
        column_data = []
        for row in values:
            column_data.append(row[col_id])
        ds = pd.Series(data=column_data, name=col_name)
        all_data.append(ds)
        df = pd.concat(all_data, axis=1)
        print(df.head())

我也看到了一些 google colab 方法,但我不能使用它,因为我仅限于使用 python,关于如何解决这个问题的任何想法?

【问题讨论】:

  • 如果需要验证才能获取文件,那么您可能必须使用Selenium 来打开网页、登录和下载。
  • 我更喜欢使用 google API,因为如果我使用 selenium,我必须更改流程
  • 我可以问你关于你的问题吗? 1.在你的脚本中,sheet.values().get(###)可以用service = build('sheets', 'v4', credentials=creds)service吗?我想问一下你是否已经完成了范围的授权。 2. 关于doing other format like csv/.xlsx,你想从谷歌电子表格转换成哪个?
  • 是的,我已经完成了身份验证,我没有包含样板代码。不,我不想将其转换为谷歌表格。我只想获取 csv 文件并将其转换为数据框
  • 感谢您的回复。从您的回复中,我提出了 3 个示例脚本作为答案。你能确认一下吗?如果这些不是您期望的方向,我深表歉意。

标签: python pandas google-drive-api


【解决方案1】:

我相信你的目标和情况如下。

  • 您想从 Google Drive 上的 CSV 文件下载 CSV 数据。
  • 您可以使用 googleapis for python 从 Google 电子表格中获取值。

模式一:

在此模式中,CSV 数据是使用 googleapis 下载的。下载的 CSV 数据保存为文件。并通过Drive API v3中的“Files:get”方法获取值。

示例脚本:

file_id = "###"  # Please set the file ID of the CSV file.

service = build('drive', 'v3', credentials=creds)
request = service.files().get_media(fileId=file_id)
fh = io.FileIO("sample.csv", mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))
  • 在这种情况下,可以将 CSV 数据转换为带有df = pd.read_csv("sample.csv") 的数据框。

模式 2:

在此模式中,作为一种简单的方法,访问令牌使用来自creds。下载的 CSV 数据不会保存为文件。并通过Drive API v3中的“Files:get”方法获取值。

示例脚本:

file_id = "###"  # Please set the file ID of the CSV file.

access_token = creds.token
url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})
print(res.text)
  • 在这种情况下,可以将CSV数据直接转换为df = pd.read_csv(io.StringIO(res.text))的dataframe。

注意:

  • 在以下脚本中,请包含https://www.googleapis.com/auth/drive.readonly 和/或https://www.googleapis.com/auth/drive 的范围。当您修改范围时,请重新授权范围。这样,修改后的范围就包含在访问令牌中。请注意这一点。

参考:

【讨论】:

  • 嗯不,我实际上想在驱动器上打开 csv 文件。抱歉,为了清楚起见,将更新问题
  • @Led 感谢您的回复。在您的情况下,CSV 文件位于 Google Drive 上,您希望从 CSV 文件中检索 CSV 数据。我的理解正确吗?
  • 是的,这就是目标。从谷歌驱动器,将 csv 内容加载到数据框中。
  • @Led 感谢您的回复。我可以正确理解你的目标。我为我糟糕的英语水平道歉。从您的脚本中,我认为您想从 Google 电子表格中检索 CSV 数据。从您的回复中,我想更新我的答案。可以等一下吗?
  • 当然,我别无选择:D
猜你喜欢
  • 2021-04-29
  • 2019-10-21
  • 1970-01-01
  • 2018-07-21
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多