Python/gspread-如何一次用不同的值更新多个单元格?

2024-04-25 14:43:43 发布

您现在位置:Python中文网/ 问答频道 /正文

要更新单元格区域,请使用以下命令。

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

for cell in cell_list:
    cell.value = 'O_o'

## Update in batch
worksheet.update_cells(cell_list)

对于我的应用程序,我希望它更新整个范围,但我正在尝试为每个单元格设置不同的值。这个例子的问题是每个单元格的值都是相同的。单独更新每个单元格效率低下,而且耗时太长。我怎样才能有效地做到这一点?


Tags: in命令区域forvaluea1batchcell
3条回答

可以在包含单元格中所需不同值的单独列表中使用枚举,并使用元组的索引部分与单元格列表中的相应单元格匹配。

cell_list = worksheet.range('A1:A7')
cell_values = [1,2,3,4,5,6,7]

for i, val in enumerate(cell_values):  #gives us a tuple of an index and value
    cell_list[i].value = val    #use the index on cell_list and the val from cell_values

worksheet.update_cells(cell_list)

如果要将pandas数据帧导出到带有gspread的google工作表中,我的解决方案如下:

  • 我们不能直观地用数据框中的值(用[行,列]表示法)访问和替换单元格列表中的元素。
  • 但是,这些元素是按“行”顺序存储的“cell_list”。相对顺序取决于数据帧中的列数。元素(0,0)=>;0,5x5数据帧中的元素(3,2)为17。
    • 我们可以构造一个函数,将数据帧中的[row,col]值映射到它在列表中的位置:
def getListIndex(nrow, ncol,row_pos, col_pos):
    list_pos = row_pos*ncol + col_pos
    return(list_pos)

我们可以使用此函数使用数据框df中的相应值更新列表cell_list中的正确元素。

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]

我们可以将列表的结果“单元格列表”输出到工作表中。

worksheet.update_cells(cell_list)

假设表具有标题行,如下所示:

Name  | Weight
------+-------
Apple | 56
Pear  | 23
Leaf  | 88

那么,下面应该是不言而喻的

cell_list = []

# get the headers from row #1
headers = worksheet.row_values(1)
# find the column "Weight", we will remember this column #
colToUpdate = headers.index('Weight')

# task 1 of 2
cellLookup = worksheet.find('Leaf')
# get the cell to be updated
cellToUpdate = worksheet.cell(cellLookup.row, colToUpdate)
# update the cell's value
cellToUpdate.value = 77
# put it in the queue
cell_list.append(cellToUpdate)

# task 2 of 2
cellLookup = worksheet.find('Pear')
# get the cell to be updated
cellToUpdate = worksheet.cell(cellLookup.row, colToUpdate)
# update the cell's value
cellToUpdate.value = 28
# put it in the queue
cell_list.append(cellToUpdate)

# now, do it
worksheet.update_cells(cell_list)

相关问题 更多 >