Last active
June 14, 2023 06:16
-
-
Save divinorum-webb/61ebc59a67ec3adef2db280a17e22d40 to your computer and use it in GitHub Desktop.
Template code for downloading view data and pivoting it using Python and tableau-api-lib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
from tableau_api_lib import TableauServerConnection | |
from tableau_api_lib.sample import sample_config | |
from tableau_api_lib.utils import querying | |
from tableau_api_lib.utils.common import flatten_dict_column | |
# sample config | |
tableau_server_config = { | |
'tableau_env': { | |
'server': 'https://<YOUR_SERVER>.com', | |
'api_version': '<YOUR_API_VERSION>', | |
'username': '<YOUR_USERNAME>', | |
'password': '<YOUR_PASSWORD>', | |
'site_name': '<YOUR_SITE_NAME>', | |
'site_url': '<YOUR_SITE_URL>' | |
} | |
} | |
# configure connection and sign in | |
conn = TableauServerConnection(config, 'tableau_env') | |
conn.sign_in() | |
# query views on the site | |
site_views_df = querying.get_views_dataframe(conn) | |
# flatten the nested workbook json / dict to gain access to workbook info that helps identify the desired view | |
site_views_detailed_df = flatten_dict_column(site_views_df, keys=['name', 'id'], col_name='workbook') | |
# get views for the workbook relevant to this example | |
site_views_detailed_df[site_views_detailed_df['workbook_name'] == 'query_view_as_crosstab'] | |
# the view we want to query in this case is 'Visual C', so let's get its view ID | |
relevant_views_df = site_views_detailed_df[site_views_detailed_df['workbook_name'] == 'query_view_as_crosstab'] | |
visual_c_id = relevant_views_df[relevant_views_df['name'] == 'Visual C']['id'].to_list()[0] | |
# use the view id to query data in the view | |
view_data_raw = querying.get_view_data_dataframe(conn, view_id=visual_c_id) | |
# optionally, check the data types of your resulting Pandas DataFrame | |
# in this example, 'Sales' begins as an object (or string) column and we will change it to numerical | |
print(view_data_raw.dtypes) | |
view_data_raw['Sales'] = view_data_raw['Sales'].apply(lambda x: x.replace(',', '')) | |
view_data_raw['Sales'] = view_data_raw['Sales'].astype('float') | |
# optionally, rename any columns by calling the rename() method on your Pandas DataFrame | |
view_data_raw.rename(columns={'Year of Order Date': 'Year'}, inplace=True) | |
# finally, we can pivot our data into the form we want | |
# in this example we have 'Sub-Category' providing each row, 'Year' providing columns, and 'Sales' as the values | |
view_data_raw\ | |
.pivot_table(values=['Sales'], index=['Sub-Category'], columns=['Year']) | |
# sign out of Tableau Server | |
conn.sign_out() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment