【问题标题】:Writing a dataframe to google sheets using python/pandas使用 python/pandas 将数据框写入谷歌表格
【发布时间】: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:https://sheets.googleapis.com/v4/spreadsheets/XXX/values:batchUpdate?alt=json 时返回“'data[0].values' (type.googleapis.com/google.protobuf.ListValue) 处的值无效,“{"0": {"0":1},"1":{"0":2},"2":{"0":3},"3":{"0":4}}""。详细信息:“[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data[0].values', 'description': '无效值在“数据[0].values”(type.googleapis.com/google.protobuf.ListValue),“{“0”:{“0”:1},“1”:{“0”:2}, 2":{"0":3},"3":{"0":4}}"'}]}]">

任何指针将不胜感激。

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


    【解决方案1】:

    我相信你的目标和情况如下。

    • 您希望通过 Python 使用 googleapis 将数据框放入 Google 电子表格。
    • 您已经能够使用 Sheets API 为 Google 电子表格获取和输入值。

    对于这个,这个答案怎么样?

    修改点:

    • 我不确定数据框的值。所以在这个答案中,我想使用以下示例数据框来解释修改点。

           A  B  C
        0  1  2  3
        1  4  5  6
        2  7  8  9
      
    • 很遗憾,数据框不能直接用于“spreadsheets.values.batchUpdate”方法的请求正文。所以在这种情况下,需要将数据帧转换为二维数组。为此,我使用了tolist()

    当您的脚本使用示例数据框进行修改时,它变为如下。

    修改脚本:

    从:
    df = [[1, 2, 3, 4]]
    writer(df)
    
    到:
    sampleValue = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    df = pd.DataFrame(sampleValue, columns=list('ABC'))
    values = [df.columns.values.tolist()]
    values.extend(df.values.tolist())
    writer(values)
    

    注意:

    • 如果不想包含标题行,请进行如下修改。
      • 来自

          values = [df.columns.values.tolist()]
          values.extend(df.values.tolist())
        
      •   values = df.values.tolist()
        

    参考资料:

    【讨论】:

    • 谢谢,Tanaike,这太完美了。
    • @HamishCrichton 感谢您的回复。很高兴您的问题得到解决。
    • 请注意,如果您有日期时间并收到错误TypeError: Object of type Timestamp is not JSON serializable,只需先将相关字段转换为'str'df = df.astype('str')(将转换所有列)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多