python - 将 Pandas 数据框上传到谷歌电子表格

标签 python pandas google-sheets google-sheets-api gspread

我按照步骤操作 herehere但无法将 Pandas 数据框上传到谷歌表格。

首先我尝试了以下代码:

import gspread
from google.oauth2.service_account import Credentials

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

credentials = Credentials.from_service_account_file('my_json_file_name.json', scopes=scope)

gc = gspread.authorize(credentials)

spreadsheet_key = '1FNMkcPz3aLCaWIbrC51lgJyuDFhe2KEixTX1lsdUjOY'
wks_name = 'Sheet1'
d2g.upload(df_qrt, spreadsheet_key, wks_name, credentials=credentials, row_names=True)

上面的代码返回这样的错误信息:AttributeError: module 'df2gspread' has no attribute 'upload'这是没有意义的,因为 df2spread 确实有一个名为 upload 的函数。

其次,我尝试将我的数据附加到我在谷歌表上人为创建的数据框中,只需输入列名。这也不起作用,也没有提供任何结果。
import gspread_dataframe as gd

ws = gc.open("name_of_file").worksheet("Sheet1")
existing = gd.get_as_dataframe(ws)
updated = existing.append(df_qrt)
gd.set_with_dataframe(ws, updated)

任何帮助将不胜感激,谢谢!

最佳答案

您没有正确导入包。
就这样做

from df2gspread import df2gspread as d2g
当您使用
existing = gd.get_as_dataframe(ws)
工作表中的所有空白列和行现在都是数据框的一部分,值为 NaN,因此当您尝试将其附加到另一个数据框时,它不会被附加,因为列不匹配。
而是尝试将工作表转换为数据框
existing = pd.DataFrame(ws.get_all_records())
当您在 Google Sheets 中导出数据框时,数据框的索引存储在第一列中(在我的情况下发生过,不能确定)。
如果第一列是索引,那么您可以使用删除该列
existing.drop([''],axis=1,inplace=True)
然后这将正常工作。
updated = existing.append(df_qrt)
gd.set_with_dataframe(ws, updated)

关于python - 将 Pandas 数据框上传到谷歌电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61092662/

相关文章:

python - Pandas 数据帧错误 "tuple index out of range"

google-sheets - HLOOKUP 计算出 Google 表格中的越界错误

python - 在 Shady 中呈现预先准备好的图像阵列的一部分

python - 两个数据帧之间的操作或两个多维数组之间的操作

pandas - Python - 如何从 Excel 列创建列表

python - 用 Pandas 从excel中读取大量数据

google-analytics - 如何将多个分割添加到 Google Analytics API 报告中?

regex - 如何在非捕获组的Google表格中使用regexreplace?

python - Google App Engine 中的 SendGrid 为 "ImportError: No module named smtpapi"

python - 使用 Python 进行网页抓取