1

I need to read the Google sheet and getting the max value of a column and deleting the data to update them.

I tried to get the max value and pass to delete_rows method, but don't work well.

spreadsheet = client.open("Test")
worksheet = spreadsheet.worksheet("Test")
data = worksheet.get_all_records(head = 1, value_render_option= 'UNFORMATTED_VALUE')
dataPag = worksheet.col_values(8, value_render_option= 'UNFORMATTED_VALUE')[-1:] # Get the max value of column

Here an example in Pandas what I need

df = pd.DataFrame(data)

max = df['pages'].max()
dropLastValueDf = df.loc[(df['pages']) == max]
dfPages = df.drop(dropLastValueDf.index)

Anyone have an idea that can help me ?

2 Answers 2

0

I believe your goal is as follows.

  • You want to retrieve the rows of the maximum value from a specific column from a Google Spreadsheet.
  • You want to delete the retrieved rows.
  • You want to achieve this using gspread.

In this case, how about the following sample script?

From dataPag = worksheet.col_values(8, value_render_option= 'UNFORMATTED_VALUE')[-1:] # Get the max value of column in your script, I guessed that you might want to check column "H" (column number is 8).

Sample script:

Please set your column number to column_number.

import gspread

client = ### Please use your client.

column_number = 8  # Column H.

spreadsheet = client.open("Test")
worksheet = spreadsheet.worksheet("Test")
data = worksheet.get_all_values()[1:]
max_value = max(data, key=lambda x: x[column_number - 1])[column_number - 1]
reqs = [{
    "deleteDimension": {
        "range": {
            "sheetId": worksheet.id,
            "startIndex": i + 1,
            "endIndex": i + 2,
            "dimension": "ROWS"
        }
    }
} for i, e in enumerate(data) if e[column_number - 1] == max_value]
reqs.reverse()
spreadsheet.batch_update({"requests": reqs})

When this script is run, the following flow is run.

  1. Retrieve all values from a sheet in a Google Spreadsheet.
  2. Retrieve the rows of the maximum value from column "H".
  3. Create the request body for deleting rows.
  4. Request Sheets API and delete rows.

Reference:

Sign up to request clarification or add additional context in comments.

2 Comments

It's works, thank you ! Just needed to transform for int on lambda function int(x[column_number- 1]) and works well. Thank you @Tanaike
@Cesar Augusto Thank you for replying. I'm glad your issue was resolved. Thank you, too.
0

you can use ~ or != to remove all rows have a column pages = max value.

df = df.loc[~(df['pages']==df['pages'].max())]

# The same with
df = df.loc[(df['pages']!=df['pages'].max())]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.