简体   繁体   English

将 pandas dataframe 上传到谷歌电子表格

[英]Uploading pandas dataframe to google spreadsheet

I followed the steps here and here but couldn't upload a pandas dataframe to google sheets.我按照此处此处的步骤操作,但无法将 pandas dataframe 上传到谷歌表格。

First I tried the following code:首先我尝试了以下代码:

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)

The above code returns an error message like this: AttributeError: module 'df2gspread' has no attribute 'upload' which doesn't make sense since df2spread indeed has a function called upload.上面的代码返回如下错误消息: AttributeError: module 'df2gspread' has no attribute 'upload'这没有意义,因为 df2spread 确实有一个称为上传的 function。

Second, I tried to append my data to a dataframe that I artificially created on the google sheet by just entering the column names.其次,我尝试将我的数据 append 到一个 dataframe 中,这是我通过输入列名在谷歌表上人为创建的。 This also didn't work and didn't provide any results.这也不起作用,也没有提供任何结果。

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)

Any help will be appreciated, thanks!任何帮助将不胜感激,谢谢!

You are not importing the package properly.您没有正确导入 package。

Just do this就这样做

from df2gspread import df2gspread as d2g

When you convert a worksheet to Dataframe using当您使用将工作表转换为 Dataframe 时

existing = gd.get_as_dataframe(ws)

All the blank columns and rows in the sheet are now part of the dataframe with values as NaN, so when you try to append it with another dataframe it won't be appended because columns are mismatched.工作表中的所有空白列和行现在都是 dataframe 的一部分,其值为 NaN,因此当您尝试 append 时,它与另一个 dataframe 不匹配,因为它不会被附加。 Instead try this to covert worksheet to dataframe而是尝试将此工作表隐藏为 dataframe

existing = pd.DataFrame(ws.get_all_records())

When you export a dataframe in Google Sheets the index of the dataframe is stored in the first column(It happened in my case, can't be sure).当您在 Google 表格中导出 dataframe 时,dataframe 的索引存储在第一列中(在我的情况下发生,不能确定)。 If the first column is index then you can remove the column using如果第一列是索引,那么您可以使用删除该列

existing.drop([''],axis=1,inplace=True)

Then this will work properly.然后这将正常工作。

updated = existing.append(df_qrt)
gd.set_with_dataframe(ws, updated)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM