使用gspread在谷歌表格间复制数据遇DataFrame无法JSON序列化求解
问题解决方法
报错原因
你遇到的报错核心是gspread的update()方法仅支持传入Python原生可JSON序列化的数据(如二维列表、单个数值/字符串),不支持直接传入Pandas的DataFrame对象作为更新内容,因此触发序列化失败错误:
TypeError: Object of type DataFrame is not JSON serializable
修正方案
要实现无Excel中转的谷歌表格数据复制,按以下规则调整代码即可:
- 删掉不必要的本地Excel导出代码,全程无需本地文件作为中转
- 所有需要写入谷歌表格的Pandas对象,先转换为gspread支持的二维列表格式,同时处理NaN等Pandas专属数据类型
- 单列数据写入时,需要把每个值包裹为单独的列表元素,符合「行-列」的二维结构要求
修正后的完整代码
import gspread from oauth2client.service_account import ServiceAccountCredentials import pandas as pd import numpy as np Scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Documents\Scripts\FX Rates Query\key.json', Scope) client = gspread.authorize(creds) # 读取第一个表数据,不需要导出到本地Excel sheet = client.open("Capital").sheet1 data = sheet.get_all_records() df = pd.DataFrame(data) # 此处可直接对df做所需处理,之后转列表直接写入目标表即可,无任何本地中转 # 读取第二个表的第5列数据 sheet1 = client.open("Cash Duration ").sheet1 mgnt_fees = sheet1.col_values(5) fees = pd.DataFrame(mgnt_fees) # 筛选非0值,同时把NaN替换为空字符串避免写入报错 fees1 = fees[fees != 0].fillna('') # 将DataFrame转为二维列表,单列数据每个值单独包成列表适配行结构 fees_list = fees1.values.tolist() # 写入从B7开始的区域 update = sheet1.update('B7', fees_list)
额外说明
如果需要把第一个表Capital的内容直接写入第二个表,只需要把处理后的df用df.values.tolist()转为二维列表,直接调用目标表的update()方法写入对应区域即可,全程不需要操作本地文件。
内容的提问来源于stack exchange,提问作者user16274307
相关产品推荐
相关产品推荐

