pandas 将熊猫数据框附加到 Google 电子表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45540827/
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
Appending pandas Data Frame to Google spreadsheet
提问by BALAJI
Case: My script returns a data frame that needs has to be appended to an existing google spreadsheet as new rows of data.As of now, I'm appending a data frame as multiple single rows through gspread.
案例:我的脚本返回一个数据框,该数据框必须作为新的数据行附加到现有的谷歌电子表格中。截至目前,我通过 gspread 将数据框附加为多个单行。
My Code:
我的代码:
import gspread
import pandas as pd
df = pd.DataFrame()
# After some processing a non-empty data frame has been created.
output_conn = gc.open("SheetName").worksheet("xyz")
# Here 'SheetName' is google spreadsheet and 'xyz' is sheet in the workbook
for i, row in df.iterrows():
output_conn.append_row(row)
Is there a way to append entire data-frame rather than multiple single rows?
有没有办法附加整个数据框而不是多个单行?
回答by thorbjornwolf
I can recommend gspread-dataframe
:
我可以推荐gspread-dataframe
:
import gspread_dataframe as gd
# Connecting with `gspread` here
ws = gc.open("SheetName").worksheet("xyz")
existing = gd.get_as_dataframe(ws)
updated = existing.append(your_new_data)
gd.set_with_dataframe(ws, updated)
回答by Dark Templar
I came up with the following solution. It does not overwrite current data but just appends entire pandas DataFrame df
to the end of Sheet with name sheet
in the Spreadsheet with the name spread_sheet
.
我想出了以下解决方案。它不会覆盖当前数据,而只是将整个 Pandas DataFrame 附加df
到名称为 名称sheet
的电子表格中的 Sheet 末尾spread_sheet
。
import gspread
from google.auth.transport.requests import AuthorizedSession
from oauth2client.service_account import ServiceAccountCredentials
def append_df_to_gs(df, spread_sheet:str, sheet_name:str):
scopes = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_credentials,
scopes=scopes
)
gsc = gspread.authorize(credentials)
sheet = gsc.open(spread_sheet)
params = {'valueInputOption': 'USER_ENTERED'}
body = {'values': df.values.tolist()}
sheet.values_append(f'{sheet_name:str}!A1:G1', params, body)
For params valueInputOption
please consult this. I used USER_ENTERED
here as I needed some formulas to be valid once I append the data to Google Sheets.
对于参数,valueInputOption
请咨询这个。我USER_ENTERED
在这里使用是因为我需要一些公式才能在将数据附加到 Google 表格后有效。
回答by Anshul Sinha
if Google spreadsheet takes .csv format then you can convert a pandas dataframe to csv using df.to_csv() and save it in that format
如果 Google 电子表格采用 .csv 格式,那么您可以使用 df.to_csv() 将 Pandas 数据框转换为 csv 并将其保存为该格式