python - 将熊猫数据框上传到谷歌电子表格
问题描述
我按照此处和此处的步骤操作,但无法将熊猫数据框上传到谷歌表格。
首先我尝试了以下代码:
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 表格中导出数据框时,数据框的索引存储在第一列中(在我的情况下发生过,无法确定)。如果第一列是索引,那么您可以使用删除该列
existing.drop([''],axis=1,inplace=True)
然后这将正常工作。
updated = existing.append(df_qrt)
gd.set_with_dataframe(ws, updated)
推荐阅读
- c - 创建二叉树和函数重载并转换错误
- c - 在 C/UNIX 中使用 SIGINT 信号时遇到问题
- reactjs - 反应复制到剪贴板不触发
- c++ - 异步提升从标准输入读取的 asio
- ios - 在 SwiftUI 中,尝试使用辅助功能(sortPriority: 将 VoiceOver 聚焦在某些文本上
- r - 圆内点相对于中心的距离
- c++ - 在 Visual Studio Code 中定义 DEBUG 和 RELEASE 符号
- javascript - 如何在 React 中使用来自 axios 请求的数据填充数组
- json - 用 jq 修改嵌套对象
- java - 三维自回避随机游走的死胡同概率为零?