【发布时间】:2020-06-23 15:36:26
【问题描述】:
我正在使用 google 表格来保存共享项目的数据。我使用 Google 的 Sheets API 访问数据,在 python 中处理它,并尝试在函数编写器中使用 batchUpdate 更新 Sheets 文件。
- 如果我将此函数数据作为列表传递,它将按预期工作。
- 如果我传递了一个数据框(如我所愿),我会得到:
TypeError: Object of type DataFrame is not JSON serializable - 如果我使用
.to_json(),我会得到:
googleapiclient.errors.HttpError:
任何指针将不胜感激。
import pickle
import os.path
import pandas as pd
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from pprint import pprint
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
# Spreadsheet ID: https://docs.google.com/spreadsheets/d/XXX/edit#gid=0
SPREADSHEET_ID = 'XXX'
RANGE_NAME = 'contacts'
def writer(df):
service = build('sheets', 'v4', credentials=gsheet_api(SCOPES))
sheet_name = 'contacts'
data = [{'range' : sheet_name, 'values' : df}]
batch_update_values_request_body = {
'value_input_option': 'RAW',
'data': data }
request = service.spreadsheets().values().batchUpdate(spreadsheetId=SPREADSHEET_ID,
body=batch_update_values_request_body)
response = request.execute()
pprint(response)
df = [[1, 2, 3, 4]]
writer(df)
【问题讨论】:
标签: python pandas google-sheets google-sheets-api