使用 df2gsheets 将 pandas DF 从 python 导入 google 工作表时出现数据格式问题

Problem with data format while Importing pandas DF from python into google sheets using df2gsheets

我正在使用 df2gspread 将某个 pandas df 导入 google 工作表。该过程运行没有任何问题,但我想在 Gsheets 中操作的数字信息作为文本导入。当我对存储为文本的数据使用基本数学运算时,它可以正常工作,但是当我尝试使用表格函数(例如求和、平均值和几乎所有其他函数)时,返回的值始终为零。另外,如果我尝试在 gsheet 中手动将文本转换为数字,它没有任何效果。

代码如下:

import pandas as pd
import gspread as gs
from df2gspread import df2gspread as d2g

result = tera.execute_response("select * from table_drive")
df = pd.DataFrame(result)

scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
    'json_gsheets.json', scope)
gc = gs.authorize(credentials)

spreadsheet_key = 'insert_wks_key_here'
wks = 'import'
d2g.upload(df, spreadsheet_key, wks, credentials=credentials, row_names=False,start_cell = 'B3')

这会正确插入数据,但所有内容都以文本形式不可撤销地存在。

有人能帮忙吗?

提前致谢!

这个答案怎么样?

问题

当我看到the script of df2gspread, it seems that the method of upload uses the method of update_cells()。在这种情况下,在 gspread 中,“valueInputOption”的默认值为 RAW。 df2gspread 使用默认值。这样,放置的数字值在顶部字符处有单引号 '。我认为你的问题的原因是由于这个。

在此,为了达到您的目的,我想提出以下2种模式。

模式 1:

本模式修改了df2gspread的脚本。请修改the function of upload如下。目前阶段,我认为有3个部分。

发件人:

wks.update_cells(cell_list)

收件人:

wks.update_cells(cell_list, value_input_option='USER_ENTERED')

模式二:

在这个模式中,使用了gspread中“values_update”的方法。

示例脚本:

import pandas as pd
import gspread as gs
from df2gspread import df2gspread as d2g

result = tera.execute_response("select * from table_drive")
df = pd.DataFrame(result)

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('json_gsheets.json', scope)

gc = gs.authorize(credentials)
spreadsheet_key = 'insert_wks_key_here'
wks = 'import'
spreadsheet = gc.open_by_key(spreadsheet_key)
values = [df.columns.values.tolist()]
values.extend(df.values.tolist())
spreadsheet.values_update(wks, params={'valueInputOption': 'USER_ENTERED'}, body={'values': values})
  • 可以看到这里也用到了USER_ENTERED

参考文献: