【问题标题】:Problem with data format while Importing pandas DF from python into google sheets using df2gsheets使用df2gsheets将pandas DF从python导入谷歌表格时出现数据格式问题
【发布时间】:2020-08-05 20:33:00
【问题描述】:

我正在使用 df2gspread 将某个 pandas df 导入谷歌表格。该过程运行没有任何问题,但我想在 Gsheets 中操作的数字信息作为文本导入。当我对存储为文本的数据使用基本数学运算时,它可以工作,但是当我尝试使用表格函数(例如 sum、average 和其他任何东西)时,返回的值始终为零。另外,如果我尝试在 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')

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

谁能帮忙?

提前致谢!

【问题讨论】:

    标签: python pandas google-sheets google-sheets-api gspread


    【解决方案1】:

    这个答案怎么样?

    问题

    看到the script of df2gspread的时候,好像upload的方法使用了update_cells()的方法。在这种情况下,在 gspread 中,“valueInputOption”的默认值为RAW。并且 df2gspread 使用默认值。这样,看跌数字值在顶部字符处具有单引号'。我认为你的问题的原因是由于这个。

    在这里,为了实现你的目标,我想提出以下2种模式。

    模式一:

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

    发件人:

    wks.update_cells(cell_list)
    

    收件人:

    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

    参考资料:

    【讨论】:

    • 模式 2 完美运行,比上传方法快很多!非常感谢您的帮助。
    • @Rodolfo Conversani 感谢您的回复和测试。我很高兴你的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多