我正在使用 df2gspread 将某个 pandas df 导入到谷歌表格中。该过程运行没有任何问题,但我想在 Gsheets 中操作的数字信息会作为文本导入。当我对以文本形式存储的数据使用基本数学运算时,它可以工作,但是当我尝试使用 Sheets 函数(例如求和、平均值和几乎任何其他函数)时,返回的值始终为零。另外,如果我尝试在 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')
这会正确插入数据,但所有内容都以文本形式不可撤销地存在。
有人可以帮忙吗?
提前致谢!
这个答案怎么样?
Issue
当我看到df2gspread的脚本,似乎该方法upload
使用的方法update_cells()。在这种情况下,在 gspread 中,“valueInputOption”的默认值为RAW
。 df2gspread 使用默认值。这样,输入的数值就带有单引号'
在顶部字符处。我认为你的问题的原因就是这个。
在这里,为了实现您的目标,我想提出以下两种模式。
模式一:
在此模式中,修改了 df2gspread 的脚本。请修改的功能upload如下。现阶段我认为有3个部分。
From:
wks.update_cells(cell_list)
To:
wks.update_cells(cell_list, value_input_option='USER_ENTERED')
模式2:
在该模式中,使用了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
在这种情况下也使用。
参考:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)