Run in Google Colab
|
View source on GitHub
|
Audiences in Google Analytics let you segment your users based on shared attributes that are important to your business. Using the Audience Export methods in the Google Analytics Data API (v1beta), you can asynchronously generate and retrieve a point-in-time snapshot of the users in an audience.
Before working with audience exports, keep these key data expectations in mind:
- Snapshots and data freshness (~24 hours): An audience export is a static snapshot of the users in an audience about 24 hours before the request was made. Because audience membership data is updated once per day, we recommend requesting an audience export at most once per day, per audience.
- 72-hour expiration: Audience exports expire 72 hours after creation. To view the latest users in an audience, create a new audience export each day (or use Recurring audience lists).
- Consistent user deduplication: Audience exports always identify and deduplicate users by
userIdfirst, thendeviceId, regardless of the property's Reporting identity setting. - Active memberships without backfill: Audience exports don't contain backfilled memberships (a user must log an event after the audience is created to appear in the export) and include only memberships that haven't expired under the audience's membership duration setting.
- User limits: Standard properties return up to 2 million users (10 million considered); Analytics 360 properties return up to 200 million users (1 billion considered). Larger audiences return representative samples.
This notebook demonstrates how to use google-analytics-admin (AnalyticsAdminServiceClient) to list and select an existing audience, and google-analytics-data (BetaAnalyticsDataClient) to create, monitor, and query audience exports:
- Configure the Colab environment
- Install and initialize the Python clients
- Configure your GA property and select an audience
- Create an audience export
- Wait for the audience export to become ready
- Retrieve and filter users from the audience export
- List audience exports for a property
- Interactive audience export builder
Step 0: Configure the Colab environment
Select an AUTH_METHOD in the form below and run the cell to configure Application Default Credentials (ADC) for a Google Cloud project with the Google Analytics Data API enabled. Leave SERVICE_ACCOUNT_EMAIL empty unless you select Service Account Impersonation.
| Authentication Option | When to use it |
|---|---|
Custom OAuth Client JSON (Browser) (default) |
Browser sign-in; no Service Account or local gcloud |
Custom OAuth Client JSON (gcloud --no-browser) |
Custom OAuth via local gcloud CLI |
Service Account Impersonation |
Keyless Service Account access (org-policy friendly) |
Service Account Key JSON |
Headless testing (requires careful key management) |
Expand an option below for step-by-step setup and technical details:
Custom OAuth Client JSON (Browser) (default)
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, uploadclient_secret.json, open the printed URL, and paste thehttp://localhost/?...redirect URL (orcode) from your browser's address bar. - When to use it: Default browser-only flow—works without a service account or local
gcloud. - Prerequisites:
- Enable the Data API.
- Configure Auth Platform branding (if External/Testing, add your email in Audience > Test users).
- In Auth Platform > Clients, click Create Client > Desktop app > Create, then Download JSON (guide).
- Grant your Google account GA Viewer access (Admin > Property access management).
- Under the hood: Exchanges the authorization code via OAuth 2.0 (
http://localhostredirect) and writes a user refresh token to ADC.
Custom OAuth Client JSON (gcloud --no-browser)
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, uploadclient_secret.json, run the printed--remote-bootstrapcommand locally, and paste back the output URL (guide). - When to use it: Alternative custom OAuth flow if you have
gcloudinstalled locally and prefer--remote-bootstrapover copyinglocalhostURLs. - Prerequisites:
- Follow steps 1–4 in
Custom OAuth Client JSON (Browser)above to download a Desktop appclient_secret.jsonand grant GA Viewer access. - Install the
gcloudCLI on your local machine.
- Follow steps 1–4 in
- Under the hood: Runs
gcloud auth application-default login --no-browser --client-id-file=...and saves the bootstrapped user token to ADC.
Service Account Impersonation
- How it works: Enter
SERVICE_ACCOUNT_EMAIL(and optionalPROJECT_IDoverride), run the cell, open the printed link to sign in, and paste the verification code (guide). - When to use it: Recommended keyless option when org policies block key files or restrict GA access to service accounts.
- Prerequisites:
- Enable the Data API and IAM Credentials API.
- In IAM > Service Accounts, select the service account > Permissions > Grant access and assign your user Service Account Token Creator (docs).
- Grant the service account email GA Viewer access (Admin > Property access management).
- Under the hood: Signs in your user with
cloud-platformscope only and writes an impersonation ADC config that exchanges your user token for short-lived service account tokens via IAM Credentials API.
Service Account Key JSON
- How it works: Leave
PROJECT_IDas-is (or enterPROJECT_IDto override), run the cell, and upload the JSON key file. - When to use it: Headless/shared testing with an existing key (warning: service account keys can become a security risk if not managed carefully).
- Prerequisites:
- Enable the Data API on the service account's project.
- In IAM > Service Accounts, select the service account > Keys > Add key > Create new key > JSON > Create (guide).
- Grant the service account email GA Viewer access (Admin > Property access management).
- Under the hood: Saves the uploaded key file to the runtime, sets
GOOGLE_APPLICATION_CREDENTIALS, and activates the service account ingcloudso client libraries mint tokens directly from the private key.
# @title Colab Authentication and Quota Project Setup { display-mode: "form" }
import json
import os
import urllib.parse
AUTH_METHOD = "Custom OAuth Client JSON (Browser)" # @param ["Custom OAuth Client JSON (Browser)", "Custom OAuth Client JSON (gcloud --no-browser)", "Service Account Impersonation", "Service Account Key JSON"]
PROJECT_ID = "YOUR_PROJECT_ID" # @param {type:"string"}
SERVICE_ACCOUNT_EMAIL = "" # @param {type:"string"}
SCOPES = [
"https://www.googleapis.com/auth/analytics.readonly",
]
SCOPES_CSV = ",".join(SCOPES)
GCLOUD_OAUTH_SCOPES_CSV = ",".join(
["https://www.googleapis.com/auth/cloud-platform", *SCOPES]
)
def _optional_project_id() -> str:
project_id = PROJECT_ID.strip()
return "" if project_id == "YOUR_PROJECT_ID" else project_id
if AUTH_METHOD == "Custom OAuth Client JSON (Browser)":
from google.auth import _cloud_sdk
from google.colab import files
from google_auth_oauthlib.flow import InstalledAppFlow
project_id = _optional_project_id()
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
print("Upload your OAuth Desktop client JSON file (client_secret.json):")
uploaded = files.upload()
if not uploaded:
raise ValueError("No OAuth client JSON file was uploaded.")
client_id_file = next(iter(uploaded))
try:
oauth_flow = InstalledAppFlow.from_client_secrets_file(
client_id_file, scopes=SCOPES
)
finally:
if os.path.exists(client_id_file):
os.remove(client_id_file)
oauth_flow.redirect_uri = "http://localhost"
auth_url, _ = oauth_flow.authorization_url(
access_type="offline", prompt="consent"
)
print(
"\n1. Open this URL in your browser and complete sign-in:\n\n"
f" {auth_url}\n\n"
"2. Your browser will redirect to http://localhost/?... (an 'unable to "
"connect' page is expected).\n"
" Copy the full http://localhost/... URL from your browser's address "
"bar (or just the code=... value)."
)
auth_response = input("Paste the redirect URL or authorization code: ").strip()
if "code=" in auth_response:
parsed = urllib.parse.urlparse(auth_response)
auth_code = urllib.parse.parse_qs(parsed.query).get("code", [""])[0]
else:
auth_code = urllib.parse.unquote(auth_response)
if not auth_code:
raise ValueError("Could not extract an authorization code from input.")
oauth_flow.fetch_token(code=auth_code)
creds = oauth_flow.credentials
adc_path = _cloud_sdk.get_application_default_credentials_path()
os.makedirs(os.path.dirname(adc_path), exist_ok=True)
adc_payload = {
"type": "authorized_user",
"client_id": creds.client_id,
"client_secret": creds.client_secret,
"refresh_token": creds.refresh_token,
}
if project_id:
adc_payload["quota_project_id"] = project_id
with open(adc_path, "w", encoding="utf-8") as f:
json.dump(adc_payload, f, indent=2)
print(f"Saved Application Default Credentials to {adc_path}")
if project_id:
!gcloud config set project "{project_id}"
elif AUTH_METHOD == "Custom OAuth Client JSON (gcloud --no-browser)":
from google.colab import files
project_id = _optional_project_id()
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
print("Upload your OAuth Desktop client JSON file (client_secret.json):")
uploaded = files.upload()
if not uploaded:
raise ValueError("No OAuth client JSON file was uploaded.")
client_id_file = next(iter(uploaded))
try:
!gcloud auth application-default login --no-browser --client-id-file="{client_id_file}" --scopes="{GCLOUD_OAUTH_SCOPES_CSV}"
finally:
if os.path.exists(client_id_file):
os.remove(client_id_file)
if project_id:
!gcloud auth application-default set-quota-project "{project_id}"
!gcloud config set project "{project_id}"
elif AUTH_METHOD == "Service Account Impersonation":
project_id = _optional_project_id()
sa_email = SERVICE_ACCOUNT_EMAIL.strip()
if not sa_email:
raise ValueError(
"Please enter SERVICE_ACCOUNT_EMAIL for Service Account Impersonation."
)
os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None)
!gcloud auth application-default login --no-launch-browser --impersonate-service-account="{sa_email}" --scopes="{SCOPES_CSV}"
if project_id:
os.environ["GOOGLE_CLOUD_QUOTA_PROJECT"] = project_id
!gcloud config set project "{project_id}"
else:
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
elif AUTH_METHOD == "Service Account Key JSON":
from google.colab import auth
project_id = _optional_project_id()
auth.authenticate_service_account()
if project_id:
os.environ["GOOGLE_CLOUD_QUOTA_PROJECT"] = project_id
!gcloud config set project "{project_id}"
else:
os.environ.pop("GOOGLE_CLOUD_QUOTA_PROJECT", None)
Step 1: Install and initialize the Python clients
Install the google-analytics-data and google-analytics-admin Python client libraries, then initialize BetaAnalyticsDataClient (google.analytics.data_v1beta) for audience exports and AnalyticsAdminServiceClient (google.analytics.admin_v1alpha) for listing existing audiences. Both clients automatically use the Application Default Credentials configured in your environment.
%pip install --upgrade -q google-analytics-data google-analytics-admin
from google.analytics import admin_v1alpha
from google.analytics import data_v1beta
# Create clients using Application Default Credentials
client = data_v1beta.BetaAnalyticsDataClient()
admin_client = admin_v1alpha.AnalyticsAdminServiceClient(
client_options={
"scopes": ["https://www.googleapis.com/auth/analytics.readonly"]
}
)
print(
"BetaAnalyticsDataClient and AnalyticsAdminServiceClient initialized "
"successfully."
)
Step 2: Configure your GA property and select an audience
Enter your numeric Google Analytics PROPERTY_ID in the following form (available in the Google Analytics UI under Admin > Property settings > Property details > Property ID) and run the cell (or press Enter).
The cell calls the audiences.list method (list_audiences) of the Google Analytics Admin API (v1alpha) to retrieve the existing audiences on your property (properties/{propertyId}/audiences/{audienceId}) and renders an interactive dropdown so you can choose which audience to export.
# @title GA Property and Audience Selection { run: "auto" }
from IPython.display import display
import ipywidgets as widgets
import pandas as pd
PROPERTY_ID = "YOUR_PROPERTY_ID" # @param {type:"string"}
if "admin_client" not in globals() or "client" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
property_id_clean = PROPERTY_ID.strip().removeprefix("properties/")
if not property_id_clean or property_id_clean == "YOUR_PROPERTY_ID":
raise ValueError(
"Enter a valid numeric GA Property ID in PROPERTY_ID and run this cell."
)
property_resource = f"properties/{property_id_clean}"
print(f"Configured property resource: {property_resource}")
audiences = list(
admin_client.list_audiences(
request=admin_v1alpha.ListAudiencesRequest(parent=property_resource)
)
)
if not audiences:
raise ValueError(
f"No audiences found for {property_resource}. Create an audience in the "
"Google Analytics UI under Admin > Data display > Audiences first."
)
audiences_df = pd.DataFrame(
[
{
"display_name": aud.display_name,
"name": aud.name,
"description": aud.description,
"membership_duration_days": aud.membership_duration_days,
"ads_personalization_enabled": aud.ads_personalization_enabled,
}
for aud in audiences
]
)
print(f"Found {len(audiences_df)} audience(s) for {property_resource}:")
display(audiences_df)
audience_dropdown = widgets.Dropdown(
options=[
(f"{aud.display_name} ({aud.name})", aud.name) for aud in audiences
],
value=audiences[0].name,
description="Audience:",
style={"description_width": "initial"},
layout=widgets.Layout(width="80%"),
)
audience_resource = audience_dropdown.value
def _on_audience_selected(change: dict[str, object]) -> None:
global audience_resource
audience_resource = str(change["new"])
print(f"Selected audience resource: {audience_resource}")
audience_dropdown.observe(_on_audience_selected, names="value")
print("\nSelect an audience from the following dropdown before running Step 3:")
display(audience_dropdown)
print(f"Selected audience resource: {audience_resource}")
Step 3: Create an audience export
To create an audience export, call the create_audience_export method with an AudienceExport object specifying:
audience: The resource name of the audience being exported (properties/{propertyId}/audiences/{audienceId}), taken from your dropdown selection in Step 2.dimensions: A list ofAudienceDimensionobjects specifying which user attributes to include in the export.
The Audience export schema supports a dedicated set of dimensions:
| API Name | UI Name | Description |
|---|---|---|
userId |
User ID | The User ID specified for this user in tagging (Measure activity across platforms with User-ID). |
deviceId |
Device ID | A browser-based or mobile-app-based identifier for a unique, pseudonymous website or mobile app user (Device ID). |
isAdsPersonalizationAllowed |
Is ads personalization allowed | Returns true if the user is eligible for ads personalization, false if not eligible, or (not set) if Google Analytics can't determine eligibility. |
isLimitedAdTracking |
Is limited ad tracking | The device's Limit Ad Tracking setting (true, false, or (not set)). |
create_audience_export returns a long-running operation whose initial response payload contains the newly created AudienceExport metadata (typically in the CREATING state), including its name (such as properties/1234567/audienceExports/123) for subsequent status and query calls.
if "client" not in globals() or "data_v1beta" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
if "property_resource" not in globals():
raise RuntimeError(
"Run Step 2 with a valid PROPERTY_ID to load and select an audience first."
)
if "audience_dropdown" in globals():
audience_resource = audience_dropdown.value
elif "audience_resource" not in globals():
raise RuntimeError(
"Run Step 2 with a valid PROPERTY_ID to load and select an audience first."
)
# Define the audience export with all supported audience dimensions
audience_export_config = data_v1beta.AudienceExport(
audience=audience_resource,
dimensions=[
data_v1beta.AudienceDimension(dimension_name="userId"),
data_v1beta.AudienceDimension(dimension_name="deviceId"),
data_v1beta.AudienceDimension(
dimension_name="isAdsPersonalizationAllowed"
),
data_v1beta.AudienceDimension(dimension_name="isLimitedAdTracking"),
],
)
request = data_v1beta.CreateAudienceExportRequest(
parent=property_resource,
audience_export=audience_export_config,
)
# Make the request. Unpack the initial AudienceExport metadata immediately so
# Step 4 can poll and display readiness progress.
operation = client.create_audience_export(request=request)
raw_op = getattr(operation, "operation", None)
if raw_op is not None and raw_op.HasField("response"):
audience_export = data_v1beta.AudienceExport.deserialize(
raw_op.response.value
)
else:
audience_export = operation.result()
# Save the audience export resource name for subsequent requests
audience_export_name = audience_export.name
print(f"Audience export name: {audience_export_name}")
print(f"Audience display name: {audience_export.audience_display_name}")
print(f"Initial state: {audience_export.state.name}")
Step 4: Wait for the audience export to become ready
It might take several minutes to generate an audience export after calling create_audience_export. You can check the readiness state of an audience export by calling the get_audience_export method with the audience export's name.
The readiness state is returned in the state field:
CREATING: The export is still being generated (percentage_completedreports progress from0to100).ACTIVE: The export is ready to query (row_countandcreation_quota_tokens_chargedare populated).FAILED: The export failed to be created (error_messagedescribes the reason, such as quota exhaustion).
import time
if "client" not in globals() or "data_v1beta" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
State = data_v1beta.AudienceExport.State
def wait_for_audience_export(
name: str, poll_interval_seconds: int = 10, timeout_seconds: int = 900
) -> data_v1beta.AudienceExport:
"""Polls an audience export until it is ACTIVE, and returns the AudienceExport."""
deadline = time.monotonic() + timeout_seconds
while True:
export = client.get_audience_export(
request=data_v1beta.GetAudienceExportRequest(name=name)
)
state = export.state
pct = export.percentage_completed or 0.0
print(
f"{time.strftime('%H:%M:%S')} {name}: {state.name} "
f"({pct:.0f}% completed)"
)
if state == State.ACTIVE:
return export
if state == State.FAILED:
raise RuntimeError(
f"Audience export failed: {export.error_message}"
)
if time.monotonic() > deadline:
raise TimeoutError(
f"Audience export is still {state.name} after {timeout_seconds} "
"seconds. Re-run this cell later to check again."
)
time.sleep(poll_interval_seconds)
def print_audience_export_metadata(
export: data_v1beta.AudienceExport,
) -> None:
"""Prints configuration and status metadata about an audience export."""
dimensions = ", ".join(d.dimension_name for d in export.dimensions)
row_count = export.row_count or 0
print(f"Audience export: {export.name}")
print(f"Audience: {export.audience} ({export.audience_display_name})")
print(f"Dimensions: {dimensions}")
print(f"State: {export.state.name}")
print(f"Began creating: {export.begin_creating_time}")
print(f"Quota tokens charged: {export.creation_quota_tokens_charged}")
print(f"Total row count: {row_count:,}")
if "audience_export_name" not in globals():
raise RuntimeError("Run Step 3 first to create an audience export.")
# Wait for the audience export from Step 3 to become ready
audience_export = wait_for_audience_export(audience_export_name)
print_audience_export_metadata(audience_export)
Step 5: Retrieve and filter users from the audience export
Once the audience export is ACTIVE, call the query_audience_export method with the audience export's name to retrieve the users in the audience.
Use the optional offset and limit parameters to page through large exports (up to 10,000 rows are returned by default if limit is unspecified, with a maximum of 250,000 rows per request).
Filtering for ads personalization eligibility
Per the Audience export schema:
isAdsPersonalizationAllowed == "true": The user is eligible for personalized advertising.isAdsPersonalizationAllowed == "false": The user is not eligible for ads personalization, but can still be used for non-advertising use cases such as A/B testing and data explorations.isAdsPersonalizationAllowed == "(not set)": Google Analytics can't determine whether the user is eligible for ads personalization. For personalized ads, treat(not set)the same asfalse, because(not set)rows may include users who are not eligible for ads personalization.
from IPython.display import display
import pandas as pd
if "client" not in globals() or "data_v1beta" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
def query_audience_export_to_dataframe(
name: str, page_size: int = 10000
) -> pd.DataFrame:
"""Retrieves all user rows of an active audience export as a pandas DataFrame."""
headers: list[str] = []
rows: list[list[str]] = []
offset = 0
total_rows = 0
display_name = name
while True:
response = client.query_audience_export(
request=data_v1beta.QueryAudienceExportRequest(
name=name, offset=offset, limit=page_size
)
)
if response.audience_export:
if not headers:
headers = [
d.dimension_name for d in response.audience_export.dimensions
]
display_name = (
response.audience_export.audience_display_name or display_name
)
total_rows = response.row_count or 0
rows.extend(
[v.value for v in row.dimension_values]
for row in response.audience_rows
)
offset += len(response.audience_rows)
if not response.audience_rows or offset >= total_rows:
break
print(
f"Retrieved {len(rows):,} user(s) from '{display_name}' "
f"(total row_count: {total_rows:,})."
)
return pd.DataFrame(rows, columns=headers or None)
if "audience_export_name" not in globals():
raise RuntimeError(
"Run Step 3 and Step 4 first to create and wait for an audience export."
)
# Retrieve all users from the audience export generated in Step 4
users_df = query_audience_export_to_dataframe(audience_export_name)
display(users_df.head(20))
# For personalized advertising, keep only rows where isAdsPersonalizationAllowed is "true"
# (treating both "false" and "(not set)" as ineligible for ads personalization)
if "isAdsPersonalizationAllowed" in users_df.columns:
ads_eligible_df = users_df[
users_df["isAdsPersonalizationAllowed"] == "true"
]
print(
f"Users eligible for ads personalization: {len(ads_eligible_df):,} "
f"of {len(users_df):,}"
)
Step 6: List audience exports for a property
To view all audience exports created for a property over the last 72 hours, call the list_audience_exports method. Because audience membership data updates once per day and exports remain available for 72 hours, checking existing exports lets you reuse an ACTIVE export created earlier the same day instead of spending additional quota tokens.
from IPython.display import display
import pandas as pd
if "client" not in globals() or "data_v1beta" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
if "property_resource" not in globals():
raise RuntimeError(
"Run Step 2 with a valid PROPERTY_ID to configure your property first."
)
# Make the request. The pager handles page tokens automatically.
pager = client.list_audience_exports(
request=data_v1beta.ListAudienceExportsRequest(parent=property_resource)
)
exports_df = pd.DataFrame(
[
{
"name": export.name,
"audience": export.audience,
"audience_display_name": export.audience_display_name,
"state": export.state.name,
"begin_creating_time": export.begin_creating_time,
"dimensions": ", ".join(
d.dimension_name for d in export.dimensions
),
"row_count": export.row_count or 0,
"quota_tokens_charged": export.creation_quota_tokens_charged,
}
for export in pager
]
)
print(
f"Found {len(exports_df)} audience export(s) for {property_resource}."
)
display(exports_df)
Step 7: Interactive audience export builder
Use the following interactive form cell to export and query the audience selected in the Step 2 dropdown with your choice of audience export dimensions. When reuse_existing_active_export is enabled, the cell first checks list_audience_exports for an existing ACTIVE export with the same audience and dimensions so you don't create duplicate exports on the same day.
# @title Create or Reuse an Audience Export
import time
from IPython.display import display
import pandas as pd
include_user_id = True # @param {type:"boolean"}
include_device_id = True # @param {type:"boolean"}
include_is_ads_personalization_allowed = True # @param {type:"boolean"}
include_is_limited_ad_tracking = False # @param {type:"boolean"}
only_ads_personalization_allowed = False # @param {type:"boolean"}
reuse_existing_active_export = True # @param {type:"boolean"}
if "client" not in globals() or "data_v1beta" not in globals():
raise RuntimeError(
"Run Step 1 first to install packages and initialize the API clients."
)
if "property_resource" not in globals():
raise RuntimeError(
"Run Step 2 with a valid PROPERTY_ID to load and select an audience first."
)
if "audience_dropdown" in globals():
target_audience = audience_dropdown.value
elif "audience_resource" in globals():
target_audience = audience_resource
else:
raise RuntimeError(
"Run Step 2 with a valid PROPERTY_ID to load and select an audience first."
)
if "wait_for_audience_export" not in globals():
def wait_for_audience_export(
name: str, poll_interval_seconds: int = 10, timeout_seconds: int = 900
) -> data_v1beta.AudienceExport:
"""Polls an audience export until it is ACTIVE."""
deadline = time.monotonic() + timeout_seconds
while True:
export = client.get_audience_export(
request=data_v1beta.GetAudienceExportRequest(name=name)
)
pct = export.percentage_completed or 0.0
print(
f"{time.strftime('%H:%M:%S')} {name}: {export.state.name} "
f"({pct:.0f}% completed)"
)
if export.state == data_v1beta.AudienceExport.State.ACTIVE:
return export
if export.state == data_v1beta.AudienceExport.State.FAILED:
raise RuntimeError(f"Audience export failed: {export.error_message}")
if time.monotonic() > deadline:
raise TimeoutError(
f"Audience export is still {export.state.name} after "
f"{timeout_seconds} seconds."
)
time.sleep(poll_interval_seconds)
if "print_audience_export_metadata" not in globals():
def print_audience_export_metadata(
export: data_v1beta.AudienceExport,
) -> None:
"""Prints configuration and status metadata about an audience export."""
dims = ", ".join(d.dimension_name for d in export.dimensions)
print(f"Audience export: {export.name}")
print(f"Audience: {export.audience} ({export.audience_display_name})")
print(f"Dimensions: {dims}")
print(f"State: {export.state.name}")
print(f"Began creating: {export.begin_creating_time}")
print(f"Quota tokens charged: {export.creation_quota_tokens_charged}")
print(f"Total row count: {(export.row_count or 0):,}")
if "query_audience_export_to_dataframe" not in globals():
def query_audience_export_to_dataframe(
name: str, page_size: int = 10000
) -> pd.DataFrame:
"""Retrieves all user rows of an active audience export as a DataFrame."""
headers: list[str] = []
rows: list[list[str]] = []
offset = 0
total_rows = 0
while True:
resp = client.query_audience_export(
request=data_v1beta.QueryAudienceExportRequest(
name=name, offset=offset, limit=page_size
)
)
if resp.audience_export and not headers:
headers = [d.dimension_name for d in resp.audience_export.dimensions]
total_rows = resp.row_count or 0
rows.extend(
[v.value for v in row.dimension_values] for row in resp.audience_rows
)
offset += len(resp.audience_rows)
if not resp.audience_rows or offset >= total_rows:
break
return pd.DataFrame(rows, columns=headers or None)
selected_dimensions: list[str] = []
if include_user_id:
selected_dimensions.append("userId")
if include_device_id:
selected_dimensions.append("deviceId")
if include_is_ads_personalization_allowed or only_ads_personalization_allowed:
selected_dimensions.append("isAdsPersonalizationAllowed")
if include_is_limited_ad_tracking:
selected_dimensions.append("isLimitedAdTracking")
if not selected_dimensions:
raise ValueError("Select at least one audience export dimension.")
selected_export = None
if reuse_existing_active_export:
for existing in client.list_audience_exports(
request=data_v1beta.ListAudienceExportsRequest(parent=property_resource)
):
existing_dims = [d.dimension_name for d in existing.dimensions]
if (
existing.audience == target_audience
and existing.state == data_v1beta.AudienceExport.State.ACTIVE
and existing_dims == selected_dimensions
):
selected_export = existing
print(f"Reusing existing ACTIVE audience export: {existing.name}")
break
if selected_export is None:
create_req = data_v1beta.CreateAudienceExportRequest(
parent=property_resource,
audience_export=data_v1beta.AudienceExport(
audience=target_audience,
dimensions=[
data_v1beta.AudienceDimension(dimension_name=d)
for d in selected_dimensions
],
),
)
op = client.create_audience_export(request=create_req)
raw_op = getattr(op, "operation", None)
if raw_op is not None and raw_op.HasField("response"):
created = data_v1beta.AudienceExport.deserialize(raw_op.response.value)
else:
created = op.result()
selected_export = wait_for_audience_export(created.name)
print_audience_export_metadata(selected_export)
custom_df = query_audience_export_to_dataframe(selected_export.name)
if (
only_ads_personalization_allowed
and "isAdsPersonalizationAllowed" in custom_df.columns
):
custom_df = custom_df[
custom_df["isAdsPersonalizationAllowed"] == "true"
]
print(
f"Filtered to {len(custom_df):,} user(s) where "
"isAdsPersonalizationAllowed == 'true'."
)
display(custom_df.head(50))
Additional resources
- Create an audience export
- Audience export data expectations
- Audience export dimensions schema
- Recurring audience lists
- Get webhook notifications for your audience lists
properties.audiences.listREST API Reference (v1alpha)properties.audienceExportsREST API Reference (v1beta)- Google Analytics Data API Quotas
- Python Client Library Reference (
google-analytics-data) - Python Client Library Reference (
google-analytics-admin)
Run in Google Colab
View source on GitHub