gsheet_get_tab_as_df - jaybgager/tracertools GitHub Wiki

This function gets the data from a Google sheet tab as a Pandas DataFrame object using the gspread package.

[!NOTE] Google-sheet-related functions require a security token to be set up prior to use. Read the Google Sheets Setup for a guide on how to do this.

Arguments:

  • sheet_key (string, mandatory)
    • the unique key for identifying the Google sheet
    • can be found in the url of the sheet between /d/ and /edit?
  • tab_name (string, mandatory)
    • the name of the Google sheet tab you want to make into a DataFrame
    • "tab" is an informal term, officially these are called "worksheets" within Google's documentation
  • has_headers (boolean, optional, default=True)
    • if set to False, treats first row the same as the others and generates numeric column names for df
  • oauth (boolean, optional, default=False)
    • by default this function assumes you want to use a google service account for authentication
    • setting this to True attempts to use an OAuth token instead

Returns:

  • df (Pandas DataFrame object)
    • the data from the spreadsheet tab as a DataFrame

Examples

The following example uses this Google sheet.

First, we start with a Google sheet populated with segment info.

Default Behavior

Running the following code will pull the data from the seg_info tab as a DataFrame. By default it assumes the first row is a header and uses it to set the DataFrame's column names.

INPUT:

import tracertools as tt

tab_df = tt.gsheet_get_tab_as_df(
    sheet_key = "1Z6n5bRPx4wqfIDR4ZwUJl3-z2esScgxfLOeXzri2lOw",
    tab_name = "seg_info",
)

tab_df.head()

OUTPUT:

Header-less Data

Setting the has_headers argument to False will treat the first row as data to be included in the DataFrame's body and will instead assign default numeric names to each column.

INPUT:

import tracertools as tt

tab_df = tt.gsheet_get_tab_as_df(
    sheet_key = "1Z6n5bRPx4wqfIDR4ZwUJl3-z2esScgxfLOeXzri2lOw",
    tab_name = "seg_info",
    has_headers = False,
)

tab_df.head()

OUTPUT: