How do you change a specific row of a Google Sheet using Python?

Question:

The following code works to append the Google Sheet with a single row.

     def send_to_sheet(link, prompt, output)
        df2 = pd.DataFrame({'link': [link], 'prompt': [prompt], 'completion': [output]})
        values = df2.values.tolist()
        sh.values_append('Sheet1', {'valueInputOption': 'USER_ENTERED'}, {'values': values})

How would you change a specific row with the information instead of appending it?

Asked By: Jody

||

Answers:

If you want to put the values of values = df2.values.tolist() to the specific row you want, how about the following modification?

From:

df2 = pd.DataFrame({'link': [link], 'prompt': [prompt], 'completion': [output]})
values = df2.values.tolist()
sh.values_append('Sheet1', {'valueInputOption': 'USER_ENTERED'}, {'values': values})

To:

row = 2  # Please set row number you want to put the values.

df2 = pd.DataFrame({"link": [link], "prompt": [prompt], "completion": [output]})
values = df2.values.tolist()
sheet = sh.worksheet("Sheet1")
sheet.update("A" + str(row), values, value_input_option="USER_ENTERED")

Note:

  • From your question, I cannot know your actual Spreadsheet. But, if your 1st row is the header row including "link", "prompt", "completion", and you want to put the row value to your expected row with the corresponding columns, how about the following modification?

    • To:

        row = 2  # Please set row number you want to put the values.
      
        df2 = pd.DataFrame({"link": [link], "prompt": [prompt], "completion": [output]})
        obj = df2.to_dict()
        sheet = sh.worksheet("Sheet1")
        header = sheet.get_all_values()[0]
        values = [list(obj[h].values())[0] for h in header]
        sheet.update("A" + str(row), [values], value_input_option="USER_ENTERED")
      

Reference:

Answered By: Tanaike