pandas Gspread dataframe如何隐藏索引列?

pbpqsu0x  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(146)

我试图打印一个dataframe到谷歌电子表格,但它打印了一个额外的列,这是dataframe的索引:

我所做的只是循环一个产品列表:

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)

如何打印没有“A”列或索引的 Dataframe ?

dgjrabp2

dgjrabp21#

根据这个answer

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

或在一行中

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

你也可以在include_index=False中使用gspread-dataframe

相关问题