BAL*_*AJI 8 python pandas gspread
案例:我的脚本返回一个数据框,需要将其作为新的数据行附加到现有的谷歌电子表格.截至目前,我通过gspread将数据框作为多个单行添加.
我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
有没有办法追加整个数据框而不是多个单行?
tho*_*olf 11
我可以推荐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)
Run Code Online (Sandbox Code Playgroud)
小智 6
这是编写、追加(不将现有工作表加载到内存中)和读取到谷歌工作表的代码。
import gspread_dataframe as gd
import gspread as gs
gc = gs.service_account(filename="your/cred/file.json")
def export_to_sheets(worksheet_name,df,mode='r'):
ws = gc.open("SHEET_NAME").worksheet("worksheet_name")
if(mode=='w'):
ws.clear()
gd.set_with_dataframe(worksheet=ws,dataframe=df,include_index=False,include_column_header=True,resize=True)
return True
elif(mode=='a'):
ws.add_rows(df.shape[0])
gd.set_with_dataframe(worksheet=ws,dataframe=df,include_index=False,include_column_header=False,row=ws.row_count+1,resize=False)
return True
else:
return gd.get_as_dataframe(worksheet=ws)
df = pd.DataFrame.from_records([{'a': i, 'b': i * 2} for i in range(100)])
export_to_sheets("SHEET_NAME",df,'a')
Run Code Online (Sandbox Code Playgroud)
ws.clear()
。其次使用set_with_dataframe()上传数据框,这里注意resize=True,严格将工作表中的行和列设置为df.shape。这将有助于稍后的追加方法。resize=False因为我们要添加行并row=ws.row_count+1锚定其行值以进行追加。| 归档时间: |
|
| 查看次数: |
10273 次 |
| 最近记录: |