Search code examples
pythonpandasgoogle-sheetsgspread

Append new row in google spreadsheet with existing rows using pandas


I am trying to append new row in googlespreadsheet for that i have usied below script

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from gspread_dataframe import get_as_dataframe, set_with_dataframe
import pandas as pd

ws = gc.open("test_submit").worksheet("Oct-2019")       

d = {'Name': ['T', 'Z'], 'ID': [3, 4]}
df = pd.DataFrame(data=d)
existing = get_as_dataframe(ws)
existing = existing.dropna(how='all')
updated = existing.append(df)
set_with_dataframe(ws, updated)

but it creates the unnecessary column in the blank column header with name unnamed0, unnamed1 ....unnamed. Moreover, it, not append row in the proper format of the existing column name. Any help is appreciated


Solution

  • i have solved my problem using below script

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    from gspread_dataframe import get_as_dataframe, set_with_dataframe
    import pandas as pd
    
    ws = gc.open("test_submit").worksheet("Oct-2019")  
    
    d = {'Name': ['T', 'Z'], 'ID': [3, 4]}
    df = pd.DataFrame(data=d)
    existing = get_as_dataframe(ws)
    existing = existing.dropna(how='all')
    new_df= pd.DataFrame()
    new_df = new_df.append(existing)
    new_df = new_df.append(df)
    set_with_dataframe(ws, new_df,row=1, col=1, include_index=False, include_column_header=True,
                           resize=False, allow_formulas=True)