Search code examples
pythonpandasdataframeconcatenationgspread

Pandas Concat - gspread worksheets


I am trying to concat a list of worksheets. I have read in a google sheet using client.open_by_url().

I have tried:

worksheet_list = spreadsheet.worksheets()
df = pd.concat(worksheet_list, ignore_index=True)

But get this error: "TypeError: cannot concatenate object of type '<class 'gspread.models.Worksheet'>'; only Series and DataFrame objs are valid"

The question is does anyone know how to concat worksheets of the gspread.models type.

Any help is much appreciated in advance. Thanks.


Solution

  • A worksheet object is the wrong type to concat. You need to change it to a pandas DataFrame before merging.

     #Iterate to get dataframes.
     list_of_dfs = [pd.DataFrame(ws.get_all_records()) for ws in worksheet_list] 
    
     # Concat the list of dataframes
     df = df.concat(list_of_dfs, ignore_index=True)