Gspread dataframe how to hide index column?

Question:

I’m trying to print a dataframe to google spreadsheets but it’s printing an extra column which is the index of the dataframe:

enter image description here

What I’m doing is just looping a list of products:

def ExportToGoogleSheets(products):
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'config.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        # Open an existing spreadsheet
        gc = gspread.service_account()
        worksheet = gc.open(SHEET_NAME).sheet1

        # Get some columns back out
        dataframe = get_as_dataframe(worksheet, usecols=[1,2,3,4],header=None, skiprows=1, include_index=False)
        dataframe = dataframe.dropna(how='all')
        columns = ["NAME", "QUANTITY", "BRAND", "LOCATION"]
        dataframe.columns = columns

        for index, product in enumerate(products):    
            # Modify value
            dataframe.at[index,"NAME"]=product.name
            dataframe.at[index,"QUANTITY"]=product.quantity
            dataframe.at[index,"BRAND"]=product.brand
            dataframe.at[index,"LOCATION"]=product.location
        
        print(dataframe)

        print("Uploading data to google sheets")
        d2g.upload(dataframe, SAMPLE_SPREADSHEET_ID, SHEET_NAME)

        
    except HttpError as err:
        print(err)

How can I print the dataframe without the "A" column or the index?

Asked By: kuhi

||

Answers:

according to this answer

headers = dataframe.columns.values.tolist()
data = dataframe.values.tolist()
worksheet.update([headers] + data)

or in one line

worksheet.update([dataframe.columns.values.tolist()] + dataframe.values.tolist())

you can also use gspread-dataframe with include_index=False

Answered By: Hanna
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.