Here's my solution if you want to export a pandas data frame to a google sheet with gspread:
- We can't access and replace elements in cell_list with values in the data frame intuitively, with [row, col] notation.
- However, the elements are stored 'cell_list' are stored in a 'row-wise' order. The relative ordering depends on how many columns in your dataframe. Element (0,0) => 0, element (3,2) in a 5x5 dataframe is 17.
- We can construct a function that maps a [row, col] value from a data frame to its position in the list:
def getListIndex(nrow, ncol,row_pos, col_pos):
list_pos = row_pos*ncol + col_pos
return(list_pos)
We can use this function to update the correct element in the list, cell_list, with the respective value in the dataframe, df.
count_row = df.shape[0]
count_col = df.shape[1]
# note this outputs data from the 1st row
cell_list = worksheet.range(1,1,count_row,count_col)
for row in range(0,count_row):
for col in range(0,count_col):
list_index = getListIndex(count_row, count_col, row, col)
cell_list[list_index].value = df.iloc[row,col]
We can output the results of the list, cell_list, to our worksheet.
worksheet.update_cells(cell_list)