将谷歌表格与python DataFrame附加



我尝试用python df附加谷歌表。 谷歌工作表授权后,我尝试了这个:

sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Sheet1!A1:E100").execute()
values = result.get('values', [])
request = sheet.values().append(spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Sheet1!A1", valueInputOption="USER_ENTERED", insertDataOption="INSERT_ROWS", body={"values":df}).execute()

但它给了我类型错误:数据类型为数据帧的对象不可 JSON 序列化

所以我尝试了这个函数,它允许将数据加载和覆盖到 google 工作表中,但不能附加数据:

def iter_pd(df):
for val in df.columns:
yield val
for row in df.to_numpy():
for val in row:
if pd.isna(val):
yield ""
else:
yield val

def pandas_to_sheets(pandas_df, sheet, clear = True):
# Updates all values in a workbook to match a pandas dataframe
if clear:
sheet.clear()
(row, col) = pandas_df.shape
cells = sheet.range("A1:{}".format(gspread.utils.rowcol_to_a1(row + 1, col)))
for cell, val in zip(cells, iter_pd(pandas_df)):
cell.value = val
sheet.update_cells(cells)

pandas_to_sheets(df, workbook.worksheet("Sheet1"))

如有任何建议,我将不胜感激。

经过一番调查,我发现了一种使用df.to_json()对我有用的方法:

to_json返回一个 JSON 格式的字符串,而工作表 API 需要一个列表。 所以我使用了这个调用:

sheet.values().append(
spreadsheetId=SAMPLE_SPREADSHEET_ID,
range="Sheet1!A1",
valueInputOption="USER_ENTERED",
insertDataOption="INSERT_ROWS",
body={
"values": json.loads(df.to_json(orient='values'))
},
).execute()

事先import json

orient='values'根据工作表 API 的要求将数据格式化为仅值数组,json.loads()将生成的 json-string 解析为 python 对象(列表)

问题

代码的请求变量中的 body参数应采用字典类型,并且数据帧应转换为 json。

溶液

请求变量中的代码应如下所示(我最终复制了它,它按预期工作):

request = sheet.values().append(spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Sheet1!A1", valueInputOption="USER_ENTERED", insertDataOption="INSERT_ROWS", body={'values':df.to_json()}).execute()

最新更新