This post was originally published on this site

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 pdrnfrom sklearn.linear_model import LinearRegressionrnfrom sklearn.preprocessing import StandardScalerrnfrom sklearn.pipeline import make_pipelinernrn# Load historical training data from a CSVrntrain_df = pd.read_csv('historical_data.csv')rnrn# Separate features (X) and target (y)rnX_train = train_df[['feature_1', 'feature_2']]rny_train = train_df['target_metric']rnrn# Build and train a modeling pipelinern# The StandardScaler ensures features with different scales don't bias the modelrnmodel_pipeline = make_pipeline(StandardScaler(), LinearRegression())rnmodel_pipeline.fit(X_train, y_train)rnrn# Load new data for inference from another CSVrnnew_data_df = pd.read_csv('new_data.csv')rnX_new = new_data_df[['feature_1', 'feature_2']]rnrn# Make predictions rn# (The pipeline automatically scales the new data before predicting)rnnew_data_df['predictions'] = model_pipeline.predict(X_new)rnrnprint(new_data_df.head())"), ('language', ''), ('caption', )])]>

Now, with the .bigquery accessor, you can bypass the local training process entirely and leverage powerful ai.predict() directly on your data in BigQuery:

code_block
<ListValue: [StructValue([('code', "import pandas as pdrnimport bigframes.pandas as bpd # Enables bigquery accessorrnrn# Set a GCP project to use AI functions.rnbpd.options.bigquery.project = 'my-project' rnrntrain_df = pd.read_csv('historical_data.csv')rnnew_data_df = pd.read_csv('new_data.csv')rnrn# Make predictions with TabFMrnpredictions = train_df.bigquery.ai.predict(new_data_df, label_col='target_metric')rnprint(predictions)"), ('language', ''), ('caption', )])]>

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.

How the BigQuery accessor works

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.

Environment setup

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):

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 rnrn# Replace with your project ID rnbpd.options.bigquery.project = "my-project"'), ('language', ''), ('caption', )])]>

Once configured, you can call BigQuery AI functions directly on standard pandas objects.

Functions on pandas series

AI functions attached to a pandas `Series` accept single-column input sequences.

Example: AI.EMBED

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 pdrnrnanimals = pd.Series(['dog', 'fish'])rnanimals.bigquery.ai.embed(endpoint='text-embedding-005')rn# 0 {'result': array([ 1.78243860e-03, -1.10658340…rn# 1 {'result': array([-7.29714287e-03, 1.04725976…rn# dtype: struct<result: list, status: string>[pyarrow]”), (‘language’, ”), (‘caption’, )])]>

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')rntype(result)rn# pandas.Series"), ('language', ''), ('caption', )])]>

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.

Example: AI.SIMILARITY

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 pdrnrnanimals = pd.Series(['dog', 'fish'])rnanimals.bigquery.ai.similarity('shrimp', endpoint='text-embedding-005')rn# 0 0.629751rn# 1 0.768028rn# dtype: Float64"), ('language', ''), ('caption', )])]>

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 pdrnrnanimals = pd.Series(['dog', 'fish'])rnrandom_stuff = pd.Series(['smart phone', 'salmon'])rnrnanimals.bigquery.ai.similarity(random_stuff, endpoint='text-embedding-005')rn# 0 0.651206rn# 1 0.835251rn# dtype: Float64"), ('language', ''), ('caption', )])]>

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.

Functions on pandas DataFrames

DataFrame AI functions operate on multi-column structured tables or handle complex prompts involving multiple data inputs.

Example: AI.FORECAST

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 pdrnrndates = pd.date_range("2025-01-01", periods=14, freq="D")rnrndf = pd.DataFrame({rn "date": dates.tolist() * 2,rn "item_id": ["item_1"] * 14 + ["item_2"] * 14,rn "sales": [rn 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165,rn 50, 52, 55, 58, 60, 62, 65, 68, 70, 72, 75, 78, 80, 85,rn ],rn})rnrndf.sample(5)rn# date item_id salesrn# 15 2025-01-02 item_2 52rn# 10 2025-01-11 item_1 150rn# 24 2025-01-11 item_2 75rn# 26 2025-01-13 item_2 80rn# 7 2025-01-08 item_1 135'), ('language', ''), ('caption', )])]>

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(rn data_col="sales", rn timestamp_col="date", rn id_cols=["item_id"], rn horizon=3rn)rn# item_id forecast_timestamp forecast_value confidence_level \rn# 0 item_1 2025-01-16 00:00:00+00:00 174.257492 0.95 rn# 1 item_1 2025-01-15 00:00:00+00:00 167.466003 0.95 rn# 2 item_1 2025-01-17 00:00:00+00:00 180.491333 0.95 rn# 3 item_2 2025-01-17 00:00:00+00:00 91.99752 0.95 rn# 4 item_2 2025-01-15 00:00:00+00:00 87.950104 0.95 rn# 5 item_2 2025-01-16 00:00:00+00:00 90.050346 0.95 rn# rn# prediction_interval_lower_bound prediction_interval_upper_bound \rn# 0 175.728216 177.85742 rn# 1 169.34789 169.553343 rn# 2 178.587954 185.040092 rn# 3 79.145413 100.786089 rn# 4 82.876698 92.470649 rn# 5 81.460533 96.463373 rn# rn# ai_forecast_status rn# 0 rn# 1 rn# 2 rn# 3 rn# 4 rn# 5'), ('language', ''), ('caption', )])]>

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.

Example: AI.IF

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 pdrnrndf = pd.DataFrame({rn "animal": ["cougar", "fish"],rn "habitat": ["mountain", "grassland"]rn})rnrnprompt = (df["animal"], " lives in the ", df["habitat"])rnrndf.bigquery.ai.if_(prompt)rn# 0 Truern# 1 Falsern# dtype: boolean'), ('language', ''), ('caption', )])]>

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”`.

Get started

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!