使用 Pandas 数据框和 gspread 更新现有的谷歌表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42775419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update existing google sheet with a pandas data frame and gspread
提问by Mark Gilliland
I would like to update a particular tab in a Google Sheets document using a pandas data frame. I have reviewed the documentation on GitHub and readthedocs.io and am able to successfully update a certain range of cells using the following code:
我想使用 Pandas 数据框更新 Google Sheets 文档中的特定选项卡。我已经查看了 GitHub 和 readthedocs.io 上的文档,并且能够使用以下代码成功更新特定范围的单元格:
cell_list = sheet4.range('A1:A7')
cell_values = [1,2,3,4,5,6,7]
for i, val in enumerate(cell_values):
cell_list[i].value = val
sheet4.update_cells(cell_list)
As a beginner, I am having trouble connecting the dots and figuring out how to update the entire sheet using a Pandas data frame. The data frame will have 9 columns and up to 9,000 rows, with the number of rows varying depending on when the data frame is generated.
作为初学者,我无法连接点并弄清楚如何使用 Pandas 数据框更新整个工作表。数据框将有 9 列和多达 9,000 行,行数因数据框的生成时间而异。
Any advice is appreciated.
任何建议表示赞赏。
回答by Nithin
pygsheets have pandas support inbuild.
pygsheets 有 pandas 支持 inbuild。
import pygsheets
gc = pygsheets.authorize(service_file='file.json')
#open the google spreadsheet
sh = gc.open_by_url('url')
#select the first sheet
wks = sh[0]
#update the first sheet with df, starting at cell B2.
wks.set_dataframe(df, 'B2')
回答by Mark Gilliland
I ended up converting the pandas dataframe to a list and using the pygsheets package to update the google sheet.
我最终将 Pandas 数据框转换为列表并使用 pygsheets 包更新谷歌表。
import pygsheets
gc = pygsheets.authorize(service_file='file.json')
df = df.tolist()
#open the google spreadsheet
sh = gc.open_by_url('url')
#select the first sheet
wks = sh[0]
#update the first sheet with df, starting at cell B2.
wks.update_cells(crange='B2',values = df)
回答by Maybelinot
You can also use df2gspreadlibrary:
您还可以使用df2gspread库:
from df2gspread import df2gspread as d2g
import pandas as pd
# your DataFrame
df = pd.DataFrame(0, index=range(9000), columns=range(9))
# file ID or path to spreadsheet: '/folder/folder/spreadhsheet'
spreadsheet = '2VVfq...nhR3I'
# uploading
d2g.upload(df, spreadsheet, wks_name="second worksheet")