Imagine running advanced machine learning workflows—from forecasting and classification to high-dimensional embedding generation—without ever leaving your familiar pandas DataFrame. With the new .bigquery accessor from BigQuery DataFrames (BigFrames), that vision is now a reality. You can seamlessly invoke BigQuery's enterprise-grade AI functions directly within pandas, scaling your data science and ML pipelines on cloud infrastructure .
Take linear regression as an example. Traditionally, a pandas user who needs to run regression would have to extract data locally, manually select features, and train a custom scikit-learn model like this:
code_block <ListValue: [StructValue([('code', "import pandas as pd\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.pipeline import make_pipeline\r\n\r\n# Load historical training data from a CSV\r\ntrain_df = pd.read_csv('historical_data.csv')\r\n\r\n# Separate features (X) and target (y)\r\nX_train = train_df[['feature_1', 'feature_2']]\r\ny_train = train_df['target_metric']\r\n\r\n# Build and train a modeling pipeline\r\n# The StandardScaler ensures features with different scales don't bias the model\r\nmodel_pipeline = make_pipeline(StandardScaler(), LinearRegression())\r\nmodel_pipeline.fit(X_train, y_train)\r\n\r\n# Load new data for inference from another CSV\r\nnew_data_df = pd.read_csv('new_data.csv')\r\nX_new = new_data_df[['feature_1', 'feature_2']]\r\n\r\n# Make predictions \r\n# (The pipeline automatically scales the new data before predicting)\r\nnew_data_df['predictions'] = model_pipeline.predict(X_new)\r\n\r\nprint(new_data_df.head())"), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f44706f2150>)])]>Now, with the .bigquery accessor, you can bypass the local training process entirely and leverage powerful ai.predict() directly on your data in BigQuery:
As you can see, the ai.predict() is able to perform regression tasks directly over two pandas dataframes with a single function call, which greatly simplifies the entire ML process.
Under the hood, the .bigquery accessor uses BigQuery DataFrames library to transparently push your computations to Google Cloud. When you call an AI method like .ai.predict(), it doesn't compute the regression locally. Instead, it translates the pandas operation into Google Standard SQL, executes the corresponding foundational model (like TabFM) natively on BigQuery's infrastructure, and seamlessly returns the result as a standard pandas DataFrame. This allows you to easily process local datasets with powerful offerings unique to BigQuery.
The following sections detail additional executable code examples. You can also find them all in this notebook.
Before executing the code samples in this post, ensure you have a Google Cloud project with the following roles granted (see more at permissions for AI functions):
Run query jobs: BigQuery Job User (roles/bigquery.jobUser)
Access a foundation model in Gemini Enterprise Agent Platform: Agent Platform User (roles/aiplatform.user)
Next, install pandas and bigframes in your Jupyter environment. To enable the AI accessors, simply import the bigframes library and specify your Google Cloud project ID. This ensures all subsequent AI function calls are routed through your authorized project:
code_block <ListValue: [StructValue([('code', 'import bigframes.pandas as bpd \r\n\r\n# Replace with your project ID \r\nbpd.options.bigquery.project = "my-project"'), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f4470682690>)])]>Once configured, you can call BigQuery AI functions directly on standard pandas objects.
AI functions attached to a pandas `Series` accept single-column input sequences.
Generating vector embeddings is a fundamental step in many modern NLP and semantic search pipelines. By using the `ai.embed()` function, you can compute embeddings for an entire column of text in a single, clean expression.
code_block <ListValue: [StructValue([('code', "import pandas as pd\r\n\r\nanimals = pd.Series(['dog', 'fish'])\r\nanimals.bigquery.ai.embed(endpoint='text-embedding-005')\r\n# 0 {'result': array([ 1.78243860e-03, -1.10658340...\r\n# 1 {'result': array([-7.29714287e-03, 1.04725976...\r\n# dtype: struct<result: list<item: double>, status: string>[pyarrow]"), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f44706832d0>)])]>Behind the scenes, BigFrames converts the pandas Series for processing in BigQuery and casts the output back into a native pandas Series. From the developer’s perspective, the workflow remains entirely within pandas.
code_block <ListValue: [StructValue([('code', "result = animals.bigquery.ai.embed(endpoint='text-embedding-005')\r\ntype(result)\r\n# pandas.Series"), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f4470680590>)])]>Notice that the output of this operation is a native pandas `Series` containing the resulting embedding list. BigFrames handles the temporary BigQuery conversions, model execution, and final data formatting, ensuring that you never have to leave your familiar pandas interface.
When you need to calculate semantic closeness, the `ai.similarity()` function computes cosine similarity scores between your series elements and a target. This target can be either a scalar literal string or another series. Here is how you can compare a pandas `Series` against a scalar string to find matching concepts:
code_block <ListValue: [StructValue([('code', "import pandas as pd\r\n\r\nanimals = pd.Series(['dog', 'fish'])\r\nanimals.bigquery.ai.similarity('shrimp', endpoint='text-embedding-005')\r\n# 0 0.629751\r\n# 1 0.768028\r\n# dtype: Float64"), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f4470683f50>)])]>Similarly, you can perform pairwise comparisons between two distinct pandas `Series` objects to find semantic correlations across different datasets:
code_block <ListValue: [StructValue([('code', "import pandas as pd\r\n\r\nanimals = pd.Series(['dog', 'fish'])\r\nrandom_stuff = pd.Series(['smart phone', 'salmon'])\r\n\r\nanimals.bigquery.ai.similarity(random_stuff, endpoint='text-embedding-005')\r\n# 0 0.651206\r\n# 1 0.835251\r\n# dtype: Float64"), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f44706824d0>)])]>In both cases, the returned object is a standard pandas `Series` with floating-point similarity scores, making it immediately compatible with downstream pandas methods like filtering or sorting.
DataFrame AI functions operate on multi-column structured tables or handle complex prompts involving multiple data inputs.
Time-series forecasting typically requires a lot of boilerplate code to format timestamps, group entities, and train a model. The `ai.forecast()` function performs time-series forecasting across grouped structured data with simple, high-level parameters. To demonstrate this, you first prepare the input sample DataFrame representing historical sales data:
code_block <ListValue: [StructValue([('code', 'import pandas as pd\r\n\r\ndates = pd.date_range("2025-01-01", periods=14, freq="D")\r\n\r\ndf = pd.DataFrame({\r\n "date": dates.tolist() * 2,\r\n "item_id": ["item_1"] * 14 + ["item_2"] * 14,\r\n "sales": [\r\n 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165,\r\n 50, 52, 55, 58, 60, 62, 65, 68, 70, 72, 75, 78, 80, 85,\r\n ],\r\n})\r\n\r\ndf.sample(5)\r\n# date item_id sales\r\n# 15 2025-01-02 item_2 52\r\n# 10 2025-01-11 item_1 150\r\n# 24 2025-01-11 item_2 75\r\n# 26 2025-01-13 item_2 80\r\n# 7 2025-01-08 item_1 135'), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f4470682790>)])]>With your data prepared, you can call `ai.forecast()` directly on the DataFrame. Here, you specify the target metric, timestamp column, grouping key, and a prediction horizon of three days:
code_block <ListValue: [StructValue([('code', 'df.bigquery.ai.forecast(\r\n data_col="sales", \r\n timestamp_col="date", \r\n id_cols=["item_id"], \r\n horizon=3\r\n)\r\n# item_id forecast_timestamp forecast_value confidence_level \\\r\n# 0 item_1 2025-01-16 00:00:00+00:00 174.257492 0.95 \r\n# 1 item_1 2025-01-15 00:00:00+00:00 167.466003 0.95 \r\n# 2 item_1 2025-01-17 00:00:00+00:00 180.491333 0.95 \r\n# 3 item_2 2025-01-17 00:00:00+00:00 91.99752 0.95 \r\n# 4 item_2 2025-01-15 00:00:00+00:00 87.950104 0.95 \r\n# 5 item_2 2025-01-16 00:00:00+00:00 90.050346 0.95 \r\n# \r\n# prediction_interval_lower_bound prediction_interval_upper_bound \\\r\n# 0 175.728216 177.85742 \r\n# 1 169.34789 169.553343 \r\n# 2 178.587954 185.040092 \r\n# 3 79.145413 100.786089 \r\n# 4 82.876698 92.470649 \r\n# 5 81.460533 96.463373 \r\n# \r\n# ai_forecast_status \r\n# 0 \r\n# 1 \r\n# 2 \r\n# 3 \r\n# 4 \r\n# 5'), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f4470682910>)])]>The returned DataFrame provides complete forecast values alongside statistical parameters such as confidence levels and prediction intervals. Internally, this triggers a TimesFM model that performs the trend analysis, returning neatly structured results back to your local environment as a pandas DataFrame. You can also choose the model version with the model argument. For example, pass model="TimesFM 3.0" to use the newest TimesFM model, now in Preview in BigQuery, which ranks #1 on the GIFT-Eval, FEV-Bench, and TIME forecasting benchmarks.
Filtering rows on a natural-language condition is one of the most common generative AI tasks. The `ai.if_()` function evaluates a prompt built from literal strings and DataFrame columns, and returns True or False for each row:
code_block <ListValue: [StructValue([('code', 'import pandas as pd\r\n\r\ndf = pd.DataFrame({\r\n "animal": ["cougar", "fish"],\r\n "habitat": ["mountain", "grassland"]\r\n})\r\n\r\nprompt = (df["animal"], " lives in the ", df["habitat"])\r\n\r\ndf.bigquery.ai.if_(prompt)\r\n# 0 True\r\n# 1 False\r\n# dtype: boolean'), ('language', ''), ('caption', <wagtail.rich_text.RichText object at 0x7f44706823d0>)])]>Because `ai.if_()` returns a boolean Series, you can use it directly as a pandas filter mask, for example `df[df.bigquery.ai.if_(prompt)]`. `ai.if_()` runs in optimized mode by default (optimization_mode="minimize_cost"): a local, distilled model processes the majority of rows, and only the rest are sent to Gemini, which reduces cost and latency on large datasets. To send every row to the LLM instead, set `optimization_mode` to `"maximize_quality"`.
The AI functions provided by bigquery accessor unlock advanced machine learning tools directly inside your native data structures, enabling you to solve complex AI challenges without leaving the Python ecosystem you already know.
Currently supported AI functions include the following (see the documentation for full details):
Pandas Series
embed(): Generates vector embeddings to a single column.
generate_embedding(): Generates vector embeddings to a table.
generate_table(): Performs natural language tasks and generates structured outputs.
generate_text(): Performs natural language tasks and generates free-form texts.
similarity(): Computes semantic closeness (cosine similarity) between entries.
Pandas DataFrame
classify(): Performs zero-shot classification.
forecast(): Runs time-series forecasting across grouped data using TimesFM, including the new TimesFM 3.0.
generate(): Evaluates dynamic prompts across multiple columns to generate text responses.
generate_bool(): Evaluates natural language conditions and returns booleans (True/False).
generate_double(): Evaluates a prompt and returns floating-point numbers.
generate_int(): Evaluates a prompt and returns integers.
if_(): Filters rows on a natural-language condition, using optimized mode by default to reduce cost and latency.
predict(): Runs predictive modeling, such as regression, using TabFM.
score(): Rates inputs based on a scoring system that you described.
Whether you want to generate embeddings or run full time-series forecasts, BigQuery AI functions inside pandas make scaling machine learning effortless. Give it a spin and let your data do the heavy lifting!