Python/gspread - how can I update multiple cells with DIFFERENT VALUES at once?

前端 未结 4 2126
广开言路
广开言路 2021-01-01 00:23

To update a range of cells, you use the following command.

## Select a range
cell_list = worksheet.range(\'A1:A7\')

for cell in cell_list:
    cell.value =          


        
4条回答
  •  孤城傲影
    2021-01-01 01:01

    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)
    

提交回复
热议问题